简体   繁体   中英

How to convert timestamp to date string?

如何将api返回的时间戳值(2021170519)转换为格式为HH:SS DD.MM.YY(20:21 17.05.19)的日期字符串?

If the data is unified and numbers are padded you can just access their indexes.

 var data = "2021170519"; var hh = data[0] + data[1]; var mm = data[2] + data[3]; var dd = data[4] + data[5]; var MM = data[6] + data[7]; var yyyy = data[8] + data[9]; console.log(hh + ":" + mm + " " + dd + "." + MM + "." + yyyy); 

您可以使用moment.js库并根据需要设置日期格式。

moment(timestamp).format('hh:ss dd.MM.YY');

If the format is consistent, you can dissect the string into smaller chunks with a regular expression:

 var str = '2021170519' str = str.match(/.{1,2}/g) const newStr = `${str[0]}:${str[1]} ${str[2]}.${str[3]}.${str[4]}` console.log(newStr) 

I would recommend using a library like moment.js, however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM