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

例如,HH/MM/SS格式。


当前回答

将秒格式设置为hh:mm:ss:variant的最短一行解决方案:

console.log(新日期(1549312452*1000).toISOString().slice(0,19).replace('T',''));// "2019-02-04 20:34:12"

其他回答

如果时间戳是数字整数字符串,则必须首先将其转换为整数:

<!DOCTYPE html><input type=“text”id=“Date_Timestamp”size=“50”oninput='document.getElementById(“Date_Timestamp_Conversion”).innerText=new Date(this.value)+“_(转换为本地时间)\n”+new Date(this.value).toString()+“_(转换为本地时间)\n”+new Date(this.value).toUTCString()+“_(转换为世界时、UTC、GMT、GMT+0、GMT-0)\n”+Date.parse(this.value)+“_(时间戳_日期首先转换为通用时间,然后转换为时间戳)\n”+(isNaN(this.value)?“不是数字_(时间戳到本地时间)”:new Date(parseInt(this.value))+“_(转换为本地时间))+”\n+(isNaN(this.value)?“不是数字_(时间戳转换为通用时间)”:new Date(parseInt(this.value)).toUTCString()+“_(转换为通用时)”)+“\n”+"";'><br><span id=“Date_Timestamp_Conversion”>(在上面的输入框中键入\粘贴“日期”或“时间戳”!)<br></span><br>2021 03月19日=2021 3月19日_(“年/月/日”_支持)<br>2021 03月19日=2021 3月19日_(“月/日/年”_支持)<br>2021 3月19日=无效日期_(“日/月/年”_不支持)<br><br><脚本>d=新日期();document.getElementById(“Date_Timestamp”).value=d.getFullYear()+“/”+(d.getMonth()+1)+“”/“+d.getDate()+”,“+d.toLocaleTimeString([],{hour12:false,timeZoneName:“short”});</script>

最短的

(new Date(ts*1000)+'').slice(16,24)

设ts=1549312452;让时间=(新日期(ts*1000)+“”).切片(16,24);console.log(时间);

我想使用一个像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") );

您可以使用以下函数将时间戳转换为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。

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