我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
我想使用一个像momentjs.com这样的库,这样做非常简单:
基于Unix时间戳:
var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );
基于MySQL日期字符串:
var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );
其他回答
JavaScript以毫秒为单位工作,因此您必须首先将UNIX时间戳从秒转换为毫秒。
var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
下面的代码还提供了3位毫秒,非常适合控制台日志前缀:
const timeStrGet=日期=>{const milliSecsStr=date.getMilliseconds().toString().padStart(3,“0”);返回`${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;};setInterval(()=>console.log(timeStrGet(new Date())),299);
// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
if(value < 10) {
return '0' + value;
}
return value;
}
var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours())
+ ':' + twoDigits(date.getMinutes())
+ ':' + twoDigits(date.getSeconds());
不需要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_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规范。