我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为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"
其他回答
函数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));
上述解决方案的问题是,如果小时、分钟或秒只有一个数字(即0-9),则时间可能是错误的,例如,它可能是2:3:9,但应该是02:03:09。
根据这个页面,使用Date的“toLocaleTimeString”方法似乎是一个更好的解决方案。
现在您必须使用unix时间戳:
const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");
@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);
所以,如果你有一个从十年左右开始的时间戳,就用这个。这为我省去了很多头疼的事。
function getTIMESTAMP() {
var date = new Date();
var year = date.getFullYear();
var month = ("0" + (date.getMonth() + 1)).substr(-2);
var day = ("0" + date.getDate()).substr(-2);
var hour = ("0" + date.getHours()).substr(-2);
var minutes = ("0" + date.getMinutes()).substr(-2);
var seconds = ("0" + date.getSeconds()).substr(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
}
//2016-01-14 02:40:01