我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
如果时间戳是数字整数字符串,则必须首先将其转换为整数:
<!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>
其他回答
让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规范。
// 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());
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()
现代解决方案(2020年)
在新的世界中,我们应该转向标准的Intl JavaScript对象,该对象具有一个方便的DateTimeFormat构造函数和.format()方法:
函数format_time{const dtFormat=新Intl.DateTimeFormat('en-GB'{timeStyle:'中等',时区:'UTC'});return dtFormat.format(新日期(s*1e3));}console.log(format_time(12345));//"03:25:45"
永恒的解决方案
但为了与所有传统JavaScript引擎100%兼容,这里是将秒格式设置为hh:mm:ss的最短的一行解决方案:
函数format_time{return new Date(s*1e3).toISOString().slice(-13,-5);}console.log(format_time(12345));//"03:25:45"
方法Date.product.toISOString()返回时间简化的扩展ISO 8601格式,总是24或27个字符长(即YYYY-MM-DDTHH:MM:ss.sssZ或分别为±YYYY-MM-DDTHH:MM:ss.sssZ)。时区总是零UTC偏移。
此解决方案不需要任何第三方库,并且在所有浏览器和JavaScript引擎中都受支持。
试试看:
new Date(1638525320* 1e3).toISOString() //2021-12-03T09:55:20.000Z