温馨提示×

js日期格式化的两种方法

js
小云
129
2024-02-02 09:08:56
栏目: 编程语言

在JavaScript中,有多种方法可以对日期进行格式化。

方法一:使用toLocaleDateString()方法

```

var date = new Date();

var formattedDate = date.toLocaleDateString();

console.log(formattedDate);

```

该方法将根据当前地区的语言和格式化选项,返回一个格式化的日期字符串。例如,对于美国地区,返回的格式可能是"6/12/2022"。

方法二:使用Intl.DateTimeFormat对象

```

var date = new Date();

var options = { year: 'numeric', month: 'long', day: 'numeric' };

var formatter = new Intl.DateTimeFormat('en-US', options);

var formattedDate = formatter.format(date);

console.log(formattedDate);

```

该方法使用Intl.DateTimeFormat对象来对日期进行格式化。可以通过传递不同的选项来自定义日期的格式。上述例子中的选项将日期格式化为"June 12, 2022"。

这两种方法都可以根据需要对日期进行自定义格式化。

0