Change Date to specific Date format using JavaScript

Last Reply 3 months ago By pandeyism

Posted 3 months ago

Hi all, How to change date with specific format using javascript

var dateFormat = response.d;  // response.d= DD/MM/YYYY OR MM/DD/YYYY OR YYYY/MM/DD ETC...
var cur = new Date(dateFormat);

my expected output should come based on the dateformate. i tried the above code but it showing invalid date

so please drop me a solution for this.

thanks to all

regards, stellus.

Posted 3 months ago

Hi stellusmca,

Check this example. Now please take its reference and correct your code.


    <input name="Stdate" type="text" id="Stdate" style="width: 200px;" />
    <br />
    <input name="Stdate1" type="text" id="Stdate1" style="width: 200px;" />
    <br />
    <input name="Stdate2" type="text" id="Stdate2" style="width: 200px;" />
<script type="text/javascript">
    window.onload = function () {
        var dateFormat = '31/12/2017';
        var dateFormat1 = '12/31/2017';
        var dateFormat2 = '2017/12/31';
        // dd/mm/yyyy format.
        var cur = parseDate(dateFormat, 'dd/mm/yyyy');
        document.getElementById("Stdate").value = cur;
        // mm/dd/yyyy format.
        var cur = parseDate(dateFormat1, 'mm/dd/yyyy');
        document.getElementById("Stdate1").value = cur;
        // yyyy/mm/dd format.
        var cur = parseDate(dateFormat2);
        document.getElementById("Stdate2").value = cur;

    function parseDate(input, format) {
        format = format || 'yyyy-mm-dd'; // default format
        var parts = input.match(/(\d+)/g), i = 0, fmt = {};
        format.replace(/(yyyy|dd|mm)/g, function (part) { fmt[part] = i++; });
        return new Date(parts[fmt['yyyy']], parts[fmt['mm']] - 1, parts[fmt['dd']]);


By taking reference of the below link i have created the example.