Javascript 将日期格式从 YYYY-MM-DD HH:MM:SS 更改为 MM-DD-YYYY
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17032735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript change date format from YYYY-MM-DD HH:MM:SS to MM-DD-YYYY
提问by Sorin Vladu
I want to change YYYY-MM-DD HH:MM:SS
to MM-DD-YYYY
我想换YYYY-MM-DD HH:MM:SS
到MM-DD-YYYY
Example:
I have a string which represents a date in this format: 2013-06-15 03:00:00
示例:我有一个字符串表示这种格式的日期: 2013-06-15 03:00:00
I want to change this string into 06-15-2013
using JavaScript.
我想将此字符串更改为06-15-2013
使用 JavaScript。
Is there any library to do this? or should i just use JavaScript?
有没有图书馆可以做到这一点?还是我应该只使用 JavaScript?
回答by VeeTheSecond
function change(time) {
var r = time.match(/^\s*([0-9]+)\s*-\s*([0-9]+)\s*-\s*([0-9]+)(.*)$/);
return r[2]+"-"+r[3]+"-"+r[1]+r[4];
}
change("2013-06-15 03:00:00");
回答by Gokul Kav
see moment.js.. i found it very useful http://momentjs.com/
参见 moment.js .. 我发现它非常有用 http://momentjs.com/
回答by abc123
DEMO: http://jsfiddle.net/abc123/f6k3H/1/
演示:http: //jsfiddle.net/abc123/f6k3H/1/
Javascript:
Javascript:
var d = new Date();
var c = new Date('2013-06-15 03:00:00');
alert(formatDate(c));
alert(formatDate(d));
function formatDate(d)
{
var month = d.getMonth();
var day = d.getDate();
month = month + 1;
month = month + "";
if (month.length == 1)
{
month = "0" + month;
}
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
return month + '-' + day + '-' + d.getFullYear();
}
Since this doesn't use RegEx you'll notice some weirdness....Examples:
由于这不使用 RegEx,您会注意到一些奇怪的地方......例如:
d.getMonth() + 1
this is because getMonth is 0 indexed....
这是因为 getMonth 是 0 索引的....
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
this is because hours, seconds, minutes all return 1 digit when they are 1 digit...this makes them return a leading 0. The same can be done to Month and Day if desired.
这是因为小时、秒、分钟在为 1 位数时都返回 1 位数……这使它们返回前导 0。如果需要,可以对月和日执行相同的操作。