我正在使用 Polymer,并且有一个日期作为 UNIX 时间戳(例如 1487016105201),我希望将其格式化为 mm/dd/yyyy - hh/mm
.
我解决了问题...见下文:
<vaadin-grid-column>
<template class="header">BINTS01 - last scan</template>
<!--<template>[[item.BINTS01]]</template> this works-->
<template>[[_formatEpochDate(item.BINTS01)]]</template>
</vaadin-grid-column>
<script>
部分是:
<script>
Polymer({
is: 'my-view8',
properties:{
eTS : String,
},
_formatEpochDate: function(eTS){
// return eTS
var d = new Date(eTS);
var n = d.getUTCDay();
return d.toDateString()
},
});
最佳答案
Date(eTS).toUTC
不起作用至少有两个原因。
- 将
Date
作为函数调用(即不带new
的Date(eTS)
)会返回字符串,而不是 Date 对象。您需要新日期(eTS)
。 - 字符串和日期对象都没有名为
toUTC
的属性(它们也没有名为toUTC
的方法,因此toUTC()
不会”也不工作)。也许您的意思是toUTCString()
?
考虑到上述事实,您可以将代码更改为:
function _formatEpochDate(eTS) {
return new Date(eTS).toUTCString();
}
const dateString = _formatEpochDate(1487016105201);
console.log(dateString);
.as-console-wrapper{min-height:100%;}
...但这并没有给你你想要的格式。每MDN :
The value returned by
toUTCString()
is a human readable string in the UTC time zone. The format of the return value may vary according to the platform. The most common return value is a RFC-1123 formatted date stamp, which is a slightly updated version of RFC-822 date stamps.
有多种方法可以解决这个问题,包括编写自己的日期格式化程序。另一种选择是使用像 strftime 这样的库。 ,如下:
function _formatEpochDate(eTS) {
return strftime('%D - %H:%M', new Date(eTS));
}
const dateString = _formatEpochDate(1487016105201);
console.log(dateString);
.as-console-wrapper{min-height:100%;}
<script src="https://unpkg.com/strftime@0.10.0/strftime-min.js"></script>
关于javascript - 将 UNIX 时间戳转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42676141/