0

我正在尝试将 unix 时间戳转换为可读时间。我已经尝试了所有我能找到的解决方案,但没有一个仍然有效。我不想使用任何模块或框架。我很感激转换的一些帮助。(Angular)请不要链接到其他问题。我都读了。谢谢

  var unix = Math.round(+new Date()/1000);
  console.log(unix) //works


  function secondstotime(unix)
{
    var t = new Date(1970,0,1);
    t.setSeconds(unix);
    var s = t.toTimeString().substr(0,8);
    if(unix > 86399)
      s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    console.log(s);
} 
secondstotime();
4

2 回答 2

2

在 angularjs 中,您可以简单地使用日期过滤器来转换 Unix 时间戳(秒)。您只需将 Unix 时间戳乘以 1000 即可使其成为毫秒时间戳。这是代码

<p>{{1469424998 * 1000 | date:'hh:mm:ss'}}</p>

或者您可以使用一些外部库(如 mommentjs)将 Unix 时间戳(秒)转换为日期时间,如下所示

 var day = moment.unix(1469424998);
console.log(day.format("hh:mm:ss"));

我希望它会有所帮助

于 2016-07-25T06:39:05.533 回答
1

你的问题不清楚。在您当前的代码中,它会打印以下输出:

1469424998
Invalid

它打印Invalid是因为您缺少secondstotime()方法的参数。如果将参数添加到secondstotime()方法调用中,它将打印以下输出:

演示

var unix = Math.round(+new Date()/1000);
  console.log(unix) //works


  function secondstotime(unix)
  {
    var t = new Date(1970,0,1);
    t.setSeconds(unix);
    var s = t.toTimeString().substr(0,8);
    if(unix > 86399)
      s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    console.log(s);
 } 
 secondstotime(unix);

输出:

1469424875
56408173:34:35 

目前尚不清楚您到底想要什么。你能告诉我们你的预期输出吗?

于 2016-07-25T05:38:27.950 回答