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

例如,HH/MM/SS格式。


当前回答

我偏爱JacobWright的Date.format()库,它以PHP的Date()函数的风格实现JavaScript日期格式。

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

其他回答

让unix_timestamp=1549312452//基于时间戳创建新的JavaScript Date对象//乘以1000,使参数以毫秒为单位,而不是以秒为单位。var date=新日期(unix_timestamp*1000);//时间戳的小时部分var hours=date.getHours();//时间戳的分钟部分var minutes=“0”+date.getMinutes();//时间戳的秒部分var seconds=“0”+date.getSeconds();//将以10:30:23格式显示时间var formattedTime=hours+‘:‘+minutes.substr(-2)+‘:’+seconds.substr(-3);console.log(格式化时间);

有关Date对象的更多信息,请参阅MDN或ECMAScript 5规范。

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

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

这适用于PHP时间戳

变量d=1541415288860;//var d=值时间戳;//注意:变量名前使用+var date=新日期(+d);console.log(d);console.log(date.toDateString());console.log(date.getFullYear());console.log(date.getMinutes());console.log(date.getSeconds());console.log(date.getHours());console.log(date.toLocaleTimeString());

var d =val.timestamp;
var date=new Date(+d); //NB: use + before variable name

console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());

上述方法将生成此结果

1541415288860
Mon Nov 05 2018 
2018 
54 
48 
13
1:54:48 PM

有很多方法可以完美地使用时间戳。无法全部列出

参见日期/年代转换器。

您需要ParseInt,否则它将无法工作:


if (!window.a)
    window.a = new Date();

var mEpoch = parseInt(UNIX_timestamp);

if (mEpoch < 10000000000)
    mEpoch *= 1000;

------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;

有多种方法可以将unix时间戳转换为时间(HH/MM/SS)

使用new Date()-这是内置的javascriptmoment包-这是一个著名的节点模块,但这将被弃用。dayjs包-这是最新的快速增长的节点模块之一

使用新日期()

const dateTimeStr = new Date(1504052527183).toLocaleString()
const result = (dateTimeStr.split(", ")[1]).split(":").join("/")
console.log(result)

使用力矩

const moment = require('moment')
const timestampObj = moment.unix(1504052527183);
const result = timestampObj.format("HH/mm/ss")
console.log(result);

使用day.js

const dayjs = require('dayjs')
const result = dayjs(1504052527183).format("HH/mm/ss")
console.log(result);

您可以使用在线时间转换工具检查时间戳到时间的转换