Convert date format in jquery

折月煮酒 提交于 2019-12-09 11:31:14

问题


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); 
});

回答1:


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);



回答2:


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




回答3:


I think you might find you answer here: Converting string to date in js

Replace the "." with "-" to validate the date.

Edit: this is done in javascript, Jquery does not have a utillity function for date



来源:https://stackoverflow.com/questions/26549773/convert-date-format-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!