gpt4 book ai didi

javascript - 将 UNIX 时间戳转换为字符串

转载 作者:行者123 更新时间:2023-11-28 18:05:45 25 4
gpt4 key购买 nike

我正在使用 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 不起作用至少有两个原因。

  1. Date 作为函数调用(即不带 newDate(eTS))会返回字符串,而不是 Date 对象。您需要新日期(eTS)
  2. 字符串和日期对象都没有名为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com