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

例如,HH/MM/SS格式。


当前回答

这适用于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

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

其他回答

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

<!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(1638525320* 1e3).toISOString()  //2021-12-03T09:55:20.000Z

我也在寻找一个简单、简短的解决方案。这就是我创建这个函数的原因。

您可以轻松扩展功能。此功能具有我所需的所有选项。它基本上与php date函数的作用相同。

函数date_format(unix_timestamp,格式){const date=新日期(unix_timestamp*1000);常量日期对象={'Y':date.getFullYear(),'m':字符串(date.getMonth()).padStart(2,'0'),“d”:字符串(date.getDate()).padStart(2,'0'),'H':字符串(date.getHours()).padStart(2,'0'),'i':字符串(date.getMinutes()).padStart(2,'0'),“s”:字符串(date.getSeconds()).padStart(2,'0'),};var dateString='';for(格式的let字符){if(dateObject中的字符){dateString+=dateObject[char];}其他{dateString+=字符;}}return dateString;}console.log(date_format(1667127654,'H/i/s'));//12/00/54console.log(date_format(1667127654,'Y-m-d H:i:s'));//2022-10-30 12:00:54console.log(日期格式(1667127654,'d.m.Y'));//30.10.2022console.log(date_format(1667127654,'H:i:s'));//12:00:54

@Aron给出的答案有效,但对我来说不起作用,因为我试图从1980年开始转换时间戳。所以我做了如下几点改变

函数ConvertUnixTimeToDateForLeap(UNIX_Timestamp){var dateObj=新日期(1980,0,1,0,0,2,0);dateObj.setSeconds(dateObj.getSeconds()+UNIX_Timestamp);return dateObj;}document.body.innerHTML=“时间戳:”+ConvertUnixTimeToDateForLeap(1269700200);

所以,如果你有一个从十年左右开始的时间戳,就用这个。这为我省去了很多头疼的事。

另一种方式-从ISO 8601日期开始。

var时间戳=1293683278;var date=新日期(时间戳*1000);var iso=date.toISOString().match(/(\d{2}:\d{2})/)警报(iso[1]);