将Unix时间戳转换为JavaScript中的时间

我将时间做为Unix时间戳存储在MySQL数据库中,并将其发送到一些JavaScript代码。 我怎么会获得时间呢? php

例如,以HH / MM / SS格式。 git


#1楼

另外一种方式-从ISO 8601开始。 github

var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var iso = date.toISOString().match(/(\d{2}:\d{2}:\d{2})/)
alert(iso[1]);

#2楼

// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
   if(value < 10) {
    return '0' + value;
   }
   return value;
}

var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours()) 
      + ':' + twoDigits(date.getMinutes()) 
      + ':' + twoDigits(date.getSeconds());

#3楼

我偏心Jacob Wright的Date.format()库,该库以PHP的date()函数样式实现JavaScript日期格式。 数据库

new Date(unix_timestamp * 1000).format('h:i:s')

#4楼

我会考虑使用像momentjs.com这样的库,这使得这真的很简单: 函数

基于Unix时间戳: spa

var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );

基于MySQL日期字符串: .net

var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );

#5楼

若是要将Unix持续时间转换为真实的小时,分​​钟和秒,则可使用如下代码: unix

var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;
相关文章
相关标签/搜索