我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
参见日期/年代转换器。
您需要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;
其他回答
如果时间戳是数字整数字符串,则必须首先将其转换为整数:
<!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>
您可以使用以下格式(源代码):
const date = new Date(yourTimestamp).toLocaleDateString('de-DE', {
weekday: 'long',
day: '2-digit',
month: 'long',
year: 'numeric'
})
结果:
Sonntag, 01. Januar 2023
函数getDateTimeFromTimestamp(unixTimeStamp){let date=新日期(unixTimeStamp);return('0'+date.getDate()).slice(-2)+'/'+('0'+(date.getMonth()+1)).sslice(-2)+'/'+date.getFullYear()+''+('0'+date.getHours()).slice(-2')+':'+('0'+date.get-Minutes())slice(-2';}const myTime=getDateTimeFromTimestamp(1435986900000);console.log(myTime);//输出01/05/2000 11:00
将秒格式设置为hh:mm:ss:variant的最短一行解决方案:
console.log(新日期(1549312452*1000).toISOString().slice(0,19).replace('T',''));// "2019-02-04 20:34:12"
您可以使用以下函数将时间戳转换为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。