我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
下面的代码还提供了3位毫秒,非常适合控制台日志前缀:
const timeStrGet=日期=>{const milliSecsStr=date.getMilliseconds().toString().padStart(3,“0”);返回`${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;};setInterval(()=>console.log(timeStrGet(new Date())),299);
其他回答
让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规范。
Use:
var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"
时间:
var s = new Date(1504095567183).toLocaleTimeString("en-US")
console.log(s)
// expected output "3:19:27 PM"
请参见Date.protype.toLocaleDateString()
您可以使用以下函数将时间戳转换为HH:MM:SS格式:
var convertTime = function(timestamp, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
var date = timestamp ? new Date(timestamp * 1000) : new Date();
return [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds())
].join(typeof separator !== 'undefined' ? separator : ':' );
}
不传递分隔符,它使用:作为(默认)分隔符:
time = convertTime(1061351153); // --> OUTPUT = 05:45:53
如果要将/用作分隔符,只需将其作为第二个参数传递:
time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55
Demo
var convertTime=函数(时间戳,分隔符){var pad=函数(输入){return input<10?“0”+输入:输入;};var date=时间戳?new Date(时间戳*1000):new Date();返回[pad(date.getHours()),pad(date.getMinutes()),pad(date.getSeconds())].join(分隔符类型!==“undefined”?分隔符:“:”);}document.body.innerHTML=“<pre>”+JSON.stringify({920535115:转换时间(920535115,'/'),1061351153:转换时间(1061351153,“:”),1435651350:转换时间(1435651350,'-'),1487938926:转换时间(1487938926),1555135551:转换时间(1555135551,'.')},null,'\t')+'</pre>';
另请参见此Fiddle。
我想使用一个像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") );
如果要将Unix持续时间转换为实际的小时、分钟和秒,可以使用以下代码:
var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;