Linux 拨号vps windows公众号手机端

js日期格式化的两种方法

lewis 9年前 (2017-01-10) 阅读数 8 #程序编程
文章标签 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”。

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门