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

标签 javascript polymer epoch

我正在使用 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/

相关文章:

javascript - 在页面上垂直居中 videojs?

javascript - 动态获取模型的外键列名

javascript - 使用过渡动画从待办事项列表中添加/删除项目

javascript - polymer 抽屉导航面板上的调用功能

javascript - 无法使用 querySelector 在模板中找到元素 - Polymer

sql - 将数据工厂中的纪元时间转换为日期时间

1970 年格式化之前的 Perl 纪元时间

javascript - 如何在没有身份验证页面的情况下将网络表单直接发布到 Google 表格?

dart-polymer:无法从事件处理程序设置属性

sql - 仅从 PostgreSQL 中采用 Java Date 类格式的字段按年份分组