我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
不需要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 ) ) );
其他回答
您可以使用以下格式(源代码):
const date = new Date(yourTimestamp).toLocaleDateString('de-DE', {
weekday: 'long',
day: '2-digit',
month: 'long',
year: 'numeric'
})
结果:
Sonntag, 01. Januar 2023
下面的代码还提供了3位毫秒,非常适合控制台日志前缀:
const timeStrGet=日期=>{const milliSecsStr=date.getMilliseconds().toString().padStart(3,“0”);返回`${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;};setInterval(()=>console.log(timeStrGet(new Date())),299);
这适用于PHP时间戳
变量d=1541415288860;//var d=值时间戳;//注意:变量名前使用+var date=新日期(+d);console.log(d);console.log(date.toDateString());console.log(date.getFullYear());console.log(date.getMinutes());console.log(date.getSeconds());console.log(date.getHours());console.log(date.toLocaleTimeString());
var d =val.timestamp;
var date=new Date(+d); //NB: use + before variable name
console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());
上述方法将生成此结果
1541415288860
Mon Nov 05 2018
2018
54
48
13
1:54:48 PM
有很多方法可以完美地使用时间戳。无法全部列出
另一种方式-从ISO 8601日期开始。
var时间戳=1293683278;var date=新日期(时间戳*1000);var iso=date.toISOString().match(/(\d{2}:\d{2})/)警报(iso[1]);
函数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