将Date对象转换为格式化字符串的最佳方法是什么

时间:2014-06-11 06:23:50

标签: javascript string date format

我一直在寻找一种将Date对象转换为格式化字符串的好方法,但无法找到答案。

输入值是这个

1402462980000

我的输出值应采用这种格式

dddd-dd-ddTdd:dd:dd[-,+]dd:dd
E.g., 2014-06-11T15:03:00+10:00

我能想到的唯一方法是手动完成

tmpDate = new Date(1402462980000);
s1 = tmpDate.getFullYear().toString();
s2 = ('0' + tmpDate.getMonth()).slice(-2);
s3 = ('0' + tmpDate.getDate()).slice(-2);
s4 = ('0' + tmpDate.getHours()).slice(-2);
s5 = ('0' + tmpDate.getMinutes()).slice(-2);
s6 = ('0' + tmpDate.getSeconds()).slice(-2);
s7 = ('0' + (tmpDate.getHours() - tmpDate.getUTCHours())).slice(-2);
s8 = ('0' + (tmpDate.getMinutes() - tmpDate.getUTCMinutes())).slice(-2);
s1 + '-' + s2 + '-' + s3 + 'T' + s4 + ':' + s5 + ':' + s6 + '+' + s7 + ':' + s8;

这对我来说有点疯狂。我认为必须有更好的方法。如果你知道请分享你的知识:)谢谢。

0 个答案:

没有答案