[英]JS, how to format a string with no delimiters into a date
So I have a date that I get from an external custom api, that comes in as plain string format with no delimiters.所以我有一个从外部自定义 api 获得的日期,它以纯字符串格式出现,没有分隔符。
How would I format it into a date.我将如何将其格式化为日期。
String -> Date字符串 -> 日期
20090506 -> 2009-05-06 20090506 -> 2009-05-06
I have browsed around stack overflow for a solution but it seems like all the answers revolve around a string with delimiters in between.我已经浏览了堆栈溢出的解决方案,但似乎所有答案都围绕着一个中间有分隔符的字符串。
Basic regular expression with replace.带替换的基本正则表达式。
function alterFormat(ds) { return ds.toString().replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'); } console.log(alterFormat(20200220)); console.log(alterFormat(20190220)); console.log(alterFormat(20201012));
You can use substring()
to extract the year, month, and day, then you can use new Date()
to convert it into a Date object.您可以使用substring()
提取年月日,然后可以使用new Date()
将其转换为日期 object。
var date = "20090506"; var formattedDate = `${date.substring(0, 4)}-${date.substring(4, 6)}-${date.substring(6, 8)}`; console.log(formattedDate); console.log(new Date(formattedDate));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.