协慌网

登录 贡献 社区

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

我将时间存储在 MySQL 数据库中作为 Unix 时间戳,并将其发送到某些 JavaScript 代码。我怎么才能得到它的时间?

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

答案

// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();

// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

有关 Date 对象的更多信息,请参阅MDNECMAScript 5 规范

function timeConverter(UNIX_timestamp){
  var a = new Date(UNIX_timestamp * 1000);
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var year = a.getFullYear();
  var month = months[a.getMonth()];
  var date = a.getDate();
  var hour = a.getHours();
  var min = a.getMinutes();
  var sec = a.getSeconds();
  var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
  return time;
}
console.log(timeConverter(0));

JavaScript 以毫秒为单位工作,因此您首先必须将 UNIX 时间戳从秒转换为毫秒。

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...