我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
您可以使用以下函数将时间戳转换为HH:MM:SS格式:
var convertTime = function(timestamp, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
var date = timestamp ? new Date(timestamp * 1000) : new Date();
return [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds())
].join(typeof separator !== 'undefined' ? separator : ':' );
}
不传递分隔符,它使用:作为(默认)分隔符:
time = convertTime(1061351153); // --> OUTPUT = 05:45:53
如果要将/用作分隔符,只需将其作为第二个参数传递:
time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55
Demo
var convertTime=函数(时间戳,分隔符){var pad=函数(输入){return input<10?“0”+输入:输入;};var date=时间戳?new Date(时间戳*1000):new Date();返回[pad(date.getHours()),pad(date.getMinutes()),pad(date.getSeconds())].join(分隔符类型!==“undefined”?分隔符:“:”);}document.body.innerHTML=“<pre>”+JSON.stringify({920535115:转换时间(920535115,'/'),1061351153:转换时间(1061351153,“:”),1435651350:转换时间(1435651350,'-'),1487938926:转换时间(1487938926),1555135551:转换时间(1555135551,'.')},null,'\t')+'</pre>';
另请参见此Fiddle。
其他回答
不需要40 KB库的现代解决方案:
Intl.DateTimeFormat是格式化日期/时间的非文化帝国主义方式。
// Setup once
var options = {
//weekday: 'long',
//month: 'short',
//year: 'numeric',
//day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );
// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
var time = hour+':'+min+':'+sec ;
return time;
}
@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);
所以,如果你有一个从十年左右开始的时间戳,就用这个。这为我省去了很多头疼的事。
注意一些答案的零问题。例如,时间戳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
函数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));