我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
有多种方法可以将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);
您可以使用在线时间转换工具检查时间戳到时间的转换
其他回答
不需要40 KB库的现代解决方案:
Intl.DateTimeFormat是格式化日期/时间的非文化帝国主义方式。
// Setup once
var options = {
//weekday: 'long',
//month: 'short',
//year: 'numeric',
//day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );
// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );
UNIX时间戳是自1970年1月1日00:00:00 UTC以来的秒数(根据维基百科)。
Javascript中Date对象的参数是自1970年1月1日00:00:00 UTC以来的毫秒数(根据W3Schools Javascript文档)。
例如,请参见以下代码:
function tm(unix_tm) {
var dt = new Date(unix_tm*1000);
document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');
}
tm(60);
tm(86400);
给予:
1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)
function getTIMESTAMP() {
var date = new Date();
var year = date.getFullYear();
var month = ("0" + (date.getMonth() + 1)).substr(-2);
var day = ("0" + date.getDate()).substr(-2);
var hour = ("0" + date.getHours()).substr(-2);
var minutes = ("0" + date.getMinutes()).substr(-2);
var seconds = ("0" + date.getSeconds()).substr(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
}
//2016-01-14 02:40:01
试试看:
new Date(1638525320* 1e3).toISOString() //2021-12-03T09:55:20.000Z
使用Moment.js,您可以获得如下时间和日期:
var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");
而且你只能使用这个:
var timeString = moment(1439198499).format("HH:mm:ss");