简体   繁体   English

如何在反应原生和/或 javascript 中将欧洲日期格式转换为日期 Object?

[英]How to convert european date format to Date Object in react native and/or javascript?

Given a date such as November 23, 2021 in this European format: 23/11/2021.给定日期,例如 2021 年 11 月 23 日,采用这种欧洲格式:23/11/2021。 I try converting it to a date object like this:我尝试将其转换为日期 object ,如下所示:

const dateString =  '23/11/2021'
const dateObj = new Date(dateString)

However, this is giving me an error saying this is an invalid date.但是,这给了我一个错误,说这是一个无效的日期。 I don't want to just convert it to the US date format, since I am trying to see if I can sort the dates given the European format.我不想将其转换为美国日期格式,因为我想看看是否可以对给定欧洲格式的日期进行排序。 Anyone know how I can convert this to a date object given the european date format?任何人都知道我如何将其转换为日期 object 给定欧洲日期格式?

If the format is always dd.MM.yyyy it can be done by slicing the date string to get the year, month and day required to create the Date object.如果格式始终为dd.MM.yyyy ,则可以通过对日期字符串进行切片来获取创建日期 object 所需的年、月和日。

 const date = '23/11/2021' let d = date.slice(0,2), m = date.slice(3,5), y = date.slice(6,10); const dateObj = new Date(y, m, d) console.log(dateObj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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