[英]Convert UNIX timestamp to string
I'm using Polymer and I have a date as a UNIX timestamp (eg 1487016105201) that I want to format as mm/dd/yyyy - hh/mm
. 我正在使用Polymer,并且有一个日期要作为UNIX时间戳(例如1487016105201),我想将其格式化为
mm/dd/yyyy - hh/mm
。
I resolved the problem... see below: 我解决了这个问题...见下文:
<vaadin-grid-column>
<template class="header">BINTS01 - last scan</template>
<!--<template>[[item.BINTS01]]</template> this works-->
<template>[[_formatEpochDate(item.BINTS01)]]</template>
</vaadin-grid-column>
The <script>
section is: <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()
},
});
There are at least two reasons why Date(eTS).toUTC
isn't working. Date(eTS).toUTC
无法正常运行至少有两个原因。
Date
as a function (ie Date(eTS)
without new
) returns a string, not a Date object. Date
作为函数调用(即不带new
Date(eTS)
)将返回字符串,而不是Date对象。 You want new Date(eTS)
. new Date(eTS)
。 toUTC
(nor do they have a method named toUTC
, so toUTC()
won't work either). toUTC
(他们也没有一个名为方法toUTC
,所以toUTC()
不会工作)。 Maybe you meant toUTCString()
? toUTCString()
? With the above facts in mind, you could change your code to this: 考虑到上述事实,您可以将代码更改为此:
function _formatEpochDate(eTS) { return new Date(eTS).toUTCString(); } const dateString = _formatEpochDate(1487016105201); console.log(dateString);
.as-console-wrapper{min-height:100%;}
...but that doesn't give you your desired format. ...但是那并不能为您提供所需的格式。 Per MDN :
每个MDN :
The value returned by
toUTCString()
is a human readable string in the UTC time zone.toUTCString()
返回的值是UTC时区中的人类可读字符串。 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.
最常见的返回值是RFC-1123格式的日期戳,这是RFC-822日期戳的稍有更新的版本。
There are a variety of ways you could solve this, including writing your own date formatter. 您可以通过多种方式解决此问题,包括编写自己的日期格式程序。 Another option is to use a library like strftime , as below:
另一个选择是使用类似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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.