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

新手上路,请多包涵

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

例如, HH/MM/SS 格式。

原文由 roflwaffle 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 736
2 个回答
 let unix_timestamp = 1549312452
 // 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);

 console.log(formattedTime);

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

原文由 Aron Rotteveel 发布,翻译遵循 CC BY-SA 4.0 许可协议

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));

原文由 shomrat 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题