在 JavaScript 中将 dd/mm/yyyy 字符串转换为日期

在 JavaScript 中将 dd/mm/yyyy 字符串转换为日期

Convert a dd/mm/yyyy string to a Date in JavaScript

要将dd/mm/yyyy字符串转换为日期:

  1. 拆分每个正斜杠上的字符串以获得日、月和年。
  2. 将年、月减1和日传递给Date()构造函数。
  3. 构造Date()函数创建并返回一个新Date对象。
索引.js
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
方法在每个正斜杠上拆分字符串
/

该方法返回一个包含子字符串的数组。

索引.js
const str = '22/04/2022'; // 👇️ ['22', '04', '2022'] console.log(str.split('/'));

我们使用数组解构在单个语句中将值分配给变量。

Date()
构造函数将
,
year( month0 = January to 11 = December),
day of the month, hours,minutesseconds作为参数并返回一个
Date对象。


在将字符串传递给

构造函数时,
我们使用
一元加号 (+)运算符将字符串转换为数字。Date()

1请注意,我们在将它传递给Date()
构造函数时从月份
中减去。

这是因为,Date构造函数需要一个从零开始的值,其中 January = 0、February = 1、March = 2 等。

下面是一个将格式化为对象的日期和时间字符串转换的
dd/mm/yyyy hh:mm:ss示例Date

索引.js
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 then had to split the date string on each forward slash to get the value for the day, month and year. The approach is the same even if the separator is different, e.g. a hyphen.

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.

This is because, the 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.