Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

javascript - 将JavaScript日期格式设置为yyyy-mm-dd(Format JavaScript date as yyyy-mm-dd)

I have a date with the format Sun May 11,2014 .

(我有一个日期为Sun May 11,2014 。)

How can I convert it to 2014-05-11 using JavaScript?

(如何使用JavaScript将其转换为2014-05-11 ?)

function taskDate(dateMilli) {
    var d = (new Date(dateMilli) + '').split(' ');
    d[2] = d[2] + ',';

    return [d[0], d[1], d[2], d[3]].join(' ');
}

var datemilli = Date.parse('Sun May 11,2014');
taskdate(datemilli);

The code above gives me the same date format, sun may 11,2014 .

(上面的代码为我提供了相同的日期格式,即sun may 11,2014 。)

How can I fix this?

(我怎样才能解决这个问题?)

  ask by user3625547 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do:

(你可以做:)

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}

Usage example:

(用法示例:)

alert(formatDate('Sun May 11,2014'));

Output:

(输出:)

2014-05-11

Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/

(JSFiddle上的演示: http : //jsfiddle.net/abdulrauf6182012/2Frm3/)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...