Convert a Unix timestamp to time in JavaScript

I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?

For example, in HH/MM/SS format.


// 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对象的更多信息,请参阅MDN或ECMAScript 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;
}

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

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
链接地址: http://www.djcxy.com/p/4268.html

上一篇: 如何将unix时间戳(自epoch以来的秒数)转换为Ruby DateTime?

下一篇: 将Unix时间戳转换为JavaScript中的时间