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

例如,HH/MM/SS格式。


当前回答

函数timeConverter(UNIX_timestamp){var a=新日期(UNIX_timestamp*1000);var months=['Jan','Feb','Mar','Pr','May','Jun','Jul','Aug','Step','Oct','Nov','Dec'];var year=a.getFullYear();var month=月[a.getMonth()];var date=a.getDate();var hour=a.getHours();var最小值=a.获取最小值();var sec=a.getSeconds();var time=日期+“”+月份+“”+year+“”“+小时+”:“+分钟+”:”+秒;返回时间;}console.log(timeConverter(0));

其他回答

@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);

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

JavaScript以毫秒为单位工作,因此您必须首先将UNIX时间戳从秒转换为毫秒。

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...

现代解决方案(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引擎中都受支持。

函数timeConverter(UNIX_timestamp){var a=新日期(UNIX_timestamp*1000);var months=['Jan','Feb','Mar','Pr','May','Jun','Jul','Aug','Step','Oct','Nov','Dec'];var year=a.getFullYear();var month=月[a.getMonth()];var date=a.getDate();var hour=a.getHours();var最小值=a.获取最小值();var sec=a.getSeconds();var time=日期+“”+月份+“”+year+“”“+小时+”:“+分钟+”:”+秒;返回时间;}console.log(timeConverter(0));

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

您可以轻松扩展功能。此功能具有我所需的所有选项。它基本上与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