扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

js日期格式化的两种方法

扬州沐宇科技
2024-02-02 09:08:56
js

在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"。

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

扫码添加客服微信