Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date format in jquery

I need the date to show in this format 2014-11-04 as "yy mm dd"

Currently, my script still shows me Tue Nov 04 2014 00:00:00 GMT+0200 (Egypt Standard Time)

$(document).ready(function() { 
    var userDate = '04.11.2014';
    from = userDate.split(".");
    f = new Date(from[2], from[1] - 1, from[0]);
    console.log(f); 
});
like image 504
Nasser Avatar asked Oct 24 '14 14:10

Nasser


2 Answers

You can construct this using the date object's methods

var date    = new Date(userDate),
    yr      = date.getFullYear(),
    month   = date.getMonth() < 10 ? '0' + date.getMonth() : date.getMonth(),
    day     = date.getDate()  < 10 ? '0' + date.getDate()  : date.getDate(),
    newDate = yr + '-' + month + '-' + day;
console.log(newDate);
like image 143
Jared Smith Avatar answered Oct 07 '22 18:10

Jared Smith


You may try the following:

   $(document).ready(function() {
        var userDate = '04.11.2014';
        var from = userDate.split(".");
        var f = new Date(from[2], from[1], from[0]);
        var date_string = f.getFullYear() + " " + f.getMonth() + " " + f.getDate();
        console.log(date_string);
    });

Alternatively I would look into Moment.js It would be way easier to deal with dates:

$(document).ready(function() {
    var userDate = '04.11.2014';
    var date_string = moment(userDate, "DD.MM.YYYY").format("YYYY-MM-DD");
    $("#results").html(date_string);
});

MOMENT.JS DEMO: FIDDLE

like image 27
CodeGodie Avatar answered Oct 07 '22 17:10

CodeGodie