我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
注意一些答案的零问题。例如,时间戳1439329773将错误地转换为2015年8月12日0:49。
我建议使用以下方法来解决这个问题:
var timestamp = 1439329773; // replace your timestamp
var date = new Date(timestamp * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
console.log(formattedDate);
现在的结果是:
12/08/2015 00:49
其他回答
如果时间戳是数字整数字符串,则必须首先将其转换为整数:
<!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时间戳:
const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");
现代解决方案(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引擎中都受支持。
让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规范。
参见日期/年代转换器。
您需要ParseInt,否则它将无法工作:
if (!window.a)
window.a = new Date();
var mEpoch = parseInt(UNIX_timestamp);
if (mEpoch < 10000000000)
mEpoch *= 1000;
------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;