![](/img/trans.png)
[英]Format date() to eee,dd MMM YYYY,hh:mm:ss in JavaScript
[英]Format a new Date() to EEE MMM dd HH:mm:ss zzz yyyy
我有一个使用“ new date()”显示的日期/时间。
当前显示
"Thu May 31 2012 13:04:29 GMT-0500 (CDT)".
我需要这个:
"Thu May 31 13:04:29 CDT 2012".
如何格式化?
您可以使用正则表达式从标准日期字符串中提取时区。
var d = new Date();
var customFormat = d.toString().slice(0,7) + ' ' + //Day and Month
d.getDate() + ' ' + //Day number
d.toTimeString().slice(0,8) + ' ' + //HH:MM:SS
/\(.*\)/g.exec(d.toString())[0].slice(1,-1) //TimeZone
+ ' ' + d.getFullYear(); //Year
var a = new Date();
var fp = a.toDateString().substring(0, a.toDateString().length - 4);
var sp = a.toLocaleTimeString();
var tp = a.toDateString().substr(a.toDateString().length - 5);
$('.timer').html(fp + ' ' + sp + ' ' + tp);
提供的字符串在您的示例中始终具有以下格式:
var s = "Thu May 31 2012 13:04:29 GMT-0500 (CDT)";
var a = s.split(/ /);
s = a[0] + " " + a[1] + " " + a[2] + " " + a[4] + " " + a[6].substring(1, a[6].length - 1) + " " + a[3];
moment.js库非常适合格式化日期和时间。 http://momentjs.com/
例如:moment()。format('MMMM Do YYYY,h:mm:ss a'); // 2015年7月14日,上午9:29:52
// timeStamp EEE MMM d HH:mm:ss z yyyy
const timeArr = new Date().toString().split('+')[0].split(' ');
const timeStamp = timeArr.slice(0, 3).concat(timeArr.slice(4), timeArr[3]).join(' ');
timeArr创建一个按空间分割的数组。 第二行通过使用slice和concat函数重新排列数组的顺序以实现此格式=>(EEE MMM dd HH:mm:ss zzz yyyy)。 最后,使用join将其转换回字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.