在 JavaScript 中将 dd/mm/yyyy 字符串转换为日期
Convert a dd/mm/yyyy string to a Date in JavaScript
要将dd/mm/yyyy
字符串转换为日期:
- 拆分每个正斜杠上的字符串以获得日、月和年。
- 将年、月减
1
和日传递给Date()
构造函数。 - 构造
Date()
函数创建并返回一个新Date
对象。
const str = '22/04/2022'; const [day, month, year] = str.split('/'); console.log(day); // 👉️ 22 console.log(month); // 👉️ 04 console.log(year); // 👉️ 2022 const date = new Date(+year, month - 1, +day); console.log(date); // 👉️ Fri Apr 22 2022
我们使用
split
方法在每个正斜杠上拆分字符串/
。
该方法返回一个包含子字符串的数组。
const str = '22/04/2022'; // 👇️ ['22', '04', '2022'] console.log(str.split('/'));
我们使用数组解构在单个语句中将值分配给变量。
Date()
构造函数将,
year
( month
0 = January to 11 = December),
day of the month
, hours
,minutes
和seconds
作为参数并返回一个
Date
对象。
在将字符串传递给
构造函数时,我们使用
一元加号 (+)运算符将字符串转换为数字。Date()
1
请注意,我们在将它传递给Date()
构造函数时从月份中减去。
Date
构造函数需要一个从零开始的值,其中 January = 0、February = 1、March = 2 等。下面是一个将格式化为对象的日期和时间字符串转换的
dd/mm/yyyy hh:mm:ss
示例Date
。
const str = '22/04/2022 07:30:16'; const [dateComponents, timeComponents] = str.split(' '); console.log(dateComponents); // 👉️ "22/04/2022" console.log(timeComponents); // 👉️ "07:30:16" const [day, month, year] = dateComponents.split('/'); const [hours, minutes, seconds] = timeComponents.split(':'); const date = new Date(+year, month - 1, +day, +hours, +minutes, +seconds); console.log(date); // 👉️ Fri Apr 22 2022 07:30:16
The first thing we did was split the date and time string on the space, so we
can get the date and time components as separate strings.
We also split the time string on each colon and assigned the hours, minutes and
seconds to variables.
Notice that we subtracted 1
from the month when passing it to the Date()
constructor.
Date
constructor expects a zero-based value for the month, where January = 0, February = 1, March = 2, etc.We then passed all of the parameters to the Date()
constructor to create a
Date
object.