在jquery中转换日期格式

Nas*_*ser 7 javascript format jquery date

我需要日期以2014-11-04格式显示为"yy mm dd"

目前,我的剧本仍然显示我2014年11月4日00:00:00 GMT + 0200(埃及标准时间)

$(document).ready(function() { 
    var userDate = '04.11.2014';
    from = userDate.split(".");
    f = new Date(from[2], from[1] - 1, from[0]);
    console.log(f); 
});
Run Code Online (Sandbox Code Playgroud)

Jar*_*ith 15

您可以使用日期对象的方法来构造它

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);
Run Code Online (Sandbox Code Playgroud)


Cod*_*die 5

您可以尝试以下方法:

   $(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);
    });
Run Code Online (Sandbox Code Playgroud)

另外,我会调查 Moment.js处理日期会更容易:

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

MOMENT.JS DEMO:FIDDLE