在 JavaScript 中将 Unix 时间戳转换为时间 [英] Convert a Unix timestamp to time in JavaScript

查看:59
本文介绍了在 JavaScript 中将 Unix 时间戳转换为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将时间作为 Unix 时间戳存储在 MySQL 数据库中,然后发送到一些 JavaScript 代码.我如何才能抽出时间?

例如,HH/MM/SS 格式.

解决方案

let unix_timestamp = 1549312452//根据时间戳创建一个新的 JavaScript Date 对象//乘以 1000,以便参数以毫秒为单位,而不是秒.var date = new Date(unix_timestamp * 1000);//时间戳的小时部分var hours = date.getHours();//时间戳的分钟部分var 分钟 = "0" + date.getMinutes();//时间戳的秒数部分var seconds = "0" + date.getSeconds();//将以 10:30:23 格式显示时间var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);console.log(formattedTime);

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

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.

解决方案

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

For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.

这篇关于在 JavaScript 中将 Unix 时间戳转换为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆