[英]How to convert my string '310519' to date object?
I have strings with dates in format '310519' ( it's 05/31/2019 ).我有日期格式为 '310519' 的字符串(它是 05/31/2019 )。 How to convert my strings to date object?
如何将我的字符串转换为日期 object?
new Date('310519')
not working. new Date('310519')
不起作用。
Use a regex to reformat the string, then use new Date(s)
:使用正则表达式重新格式化字符串,然后使用
new Date(s)
:
var s = "310519"; s = s.replace(/(\d{2})(\d{2})(\d{2})/, '$2/$1/$3'); console.log(new Date(s));
With .replace(/(\d{2})(\d{2})(\d{2})/, '$2/$1/$3')
, you reformat the groups of two digits, bascally, swap the first and second group and insert /
separators.使用
.replace(/(\d{2})(\d{2})(\d{2})/, '$2/$1/$3')
,您重新格式化两位数的组,基本上,交换第一个第二组和插入/
分隔符。 \d{2}
matches any two digits, (...)
creates capturing groups that are referenced to with the help of placeholders like $1
, $2
, $3
from the replacement part. \d{2}
匹配任何两位数, (...)
创建捕获组,这些组在替换部件中的$1
、 $2
、 $3
等占位符的帮助下被引用。
The moment library can handle dates in whatever format you specify:时刻库可以处理您指定的任何格式的日期:
const source = "310519"; const date = moment(source, "DDMMYY"); console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.