乐闻世界logo
搜索文章和话题

JS 如何格式化日期

7 个月前提问
3 个月前修改
浏览次数31

6个答案

1
2
3
4
5
6

在JavaScript中格式化日期通常可以通过以下几种方法来实现:

1. 使用 Date 对象的内置方法

JavaScript中的Date对象带有几个方法可以用来获取日期和时间的不同部分(例如年、月、日、时、分、秒),然后你可以将这些部分拼接成任何你需要的格式。

javascript
const date = new Date(); const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); const formattedDate = `${year}-${month}-${day}`; console.log(formattedDate); // 输出格式如: "2023-03-10"

2. 使用第三方库

很多开发者为了简便会选择使用像 Moment.js 或 date-fns 这样的第三方库来处理日期和时间。这些库提供了简单的API来格式化日期。

使用 Moment.js

javascript
const moment = require('moment'); const formattedDate = moment().format('YYYY-MM-DD'); console.log(formattedDate); // 输出格式如: "2023-03-10"

使用 date-fns

javascript
const { format } = require('date-fns'); const formattedDate = format(new Date(), 'yyyy-MM-dd'); console.log(formattedDate); // 输出格式如: "2023-03-10"

3. 使用国际化API Intl.DateTimeFormat

ES6引入了一个国际化API Intl,它有一个DateTimeFormat对象可以用来格式化日期。

javascript
const date = new Date(); const formatter = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', }); const formattedDate = formatter.format(date); console.log(formattedDate); // 输出格式如: "03/10/2023"

上面的例子演示了如何使用Intl.DateTimeFormat来按照美式格式(月/日/年)来格式化日期。这个API的优势在于它支持本地化,你可以很容易地按照不同地区的习惯来格式化日期。

示例

假设我们要格式化一个日期,要求输出格式为dd/MM/yyyy HH:mm:ss,我们可以这样做:

javascript
const date = new Date(); const day = date.getDate().toString().padStart(2, '0'); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const year = date.getFullYear(); const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); const seconds = date.getSeconds().toString().padStart(2, '0'); const formattedDate = `${day}/${month}/${year} ${hours}:${minutes}:${seconds}`; console.log(formattedDate); // 输出格式如: "10/03/2023 14:20:30"

在选择哪种方法时,你要根据具体需要(例如是否需要本地化,是否希望引入额外的库等)来决定。对于简单的需求,内置的Date方法可能就足够了。而对于更复杂或特定格式的需求,则可能需要使用第三方库或Intl对象来简化代码。

2024年6月29日 12:07 回复

如果您需要对格式的控制比当前接受的答案稍微少一些,Date#toLocaleDateString则可用于创建标准的特定于区域设置的渲染。和参数让应用程序指定应使用其格式约定的语言,并允许对呈现进行一些自定义localeoptions

选项关键示例:

  1. day:
    表示当天的情况。
    可能的值为“数字”、“2 位数字”。
  2. weekday:
    工作日的表示。
    可能的值为“窄”、“短”、“长”。
  3. 年:
    年份的表示。
    可能的值为“数字”、“2 位数字”。
  4. Month:
    月份的表示。
    可能的值为“数字”、“2 位数字”、“窄”、“短”、“长”。
  5. hour:
    小时的表​​示。
    可能的值为“数字”、“2 位数字”。
  6. 分钟: 分钟的表示。
    可能的值为“数字”、“2 位数字”。
  7. 第二:
    第二个的表示。
    可能的值为“数字”、“2 位数字”。
  8. hour12:
    时间格式的表示。
    接受布尔值 true 或 false

所有这些键都是可选的。您可以根据您的要求更改选项值的数量,这也将反映每个日期时间术语的存在。

注意:如果您只想配置内容选项,但仍使用当前区域设置,则传递null第一个参数将导致错误。undefined代替使用。

对于不同的语言:

  1. **“en-US”:**美式英语
  2. **“en-GB”:**英式英语
  3. **“hi-IN”:**印地语
  4. **“ja-JP”:**日语

您可以使用更多语言选项。

例如

shell
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var today = new Date(); console.log(today.toLocaleDateString("en-US")); // 9/17/2016 console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016 console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016

运行代码片段Hide results

展开片段

您也可以使用该toLocaleString()方法来达到相同的目的。唯一的区别是这个函数提供了当你不传递任何选项时的时间。

shell
// Example 9/17/2016, 1:21:34 PM

参考:

2024年6月29日 12:07 回复

DateTimeFormat对于自定义分隔的日期格式,您必须从对象(它是 ECMAScript 国际化 API的一部分)中提取日期(或时间)组件,然后使用所需的分隔符手动创建一个字符串。

为此,您可以使用DateTimeFormat#formatToParts.您可以解构数组,但这并不理想,因为数组输出取决于区域设置:

shell
{ // example 1 let formatter = new Intl.DateTimeFormat('en'); let example = formatter.formatToParts(); console.log(example); } { // example 2 let formatter = new Intl.DateTimeFormat('hi'); let example = formatter.formatToParts(); console.log(example); }

运行代码片段Hide results

展开片段

更好的方法是将格式数组映射到结果字符串:

shell
function join(date, options, separator) { function format(option) { let formatter = new Intl.DateTimeFormat('en', option); return formatter.format(date); } return options.map(format).join(separator); } let options = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}]; let joined = join(new Date, options, '-'); console.log(joined);

运行代码片段Hide results

展开片段

DateTimeFormat您还可以使用 提取出一对一 的部分,但请注意,使用此方法时,截至 2020 年 3 月, ECMAScript 实现中在分钟和秒上出现前导零时DateTimeFormat#format存在一个错误(此错误可以通过上面的方法规避)。

shell
let date = new Date(2010, 7, 5); let year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date); let month = new Intl.DateTimeFormat('en', { month: 'short' }).format(date); let day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date); console.log(`${day}-${month}-${year}`);

运行代码片段Hide results

展开片段

当使用日期和时间时,通常值得使用库(例如luxondate-fnsmoment.js不建议用于新项目),因为该领域存在许多隐藏的复杂性。

请注意, IE10不支持上述解决方案中使用的 ECMAScript 国际化 API ( 2020 年 2 月全球浏览器市场份额为0.03%)。

2024年6月29日 12:07 回复

如果您需要使用纯 JavaScript 快速设置日期格式,请使用getDategetMonth + 1getFullYear和:getHours``getMinutes

shell
var d = new Date(); var datestring = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes(); // 16-5-2015 9:50

或者,如果您需要用零填充:

shell
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" + d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2); // 16-05-2015 09:50
2024年6月29日 12:07 回复

好吧,我想要的是将今天的日期转换为MySQL友好的日期字符串2012-06-23,例如 ,并在我的一个查询中使用该字符串作为参数。我发现的简单解决方案是这样的:

shell
var today = new Date().toISOString().slice(0, 10);

请记住,上述解决方案没有考虑您的_时区_偏移。

您可以考虑使用此函数:

shell
function toJSONLocal (date) { var local = new Date(date); local.setMinutes(date.getMinutes() - date.getTimezoneOffset()); return local.toJSON().slice(0, 10); }

如果您在一天的开始/结束时执行此代码,这将为您提供正确的日期。

shell
var date = new Date(); function toLocal(date) { var local = new Date(date); local.setMinutes(date.getMinutes() - date.getTimezoneOffset()); return local.toJSON(); } function toJSONLocal(date) { var local = new Date(date); local.setMinutes(date.getMinutes() - date.getTimezoneOffset()); return local.toJSON().slice(0, 10); } // check out your devtools console console.log(date.toJSON()); console.log(date.toISOString()); console.log(toLocal(date)); console.log(toJSONLocal(date));

运行代码片段Hide results

展开片段

2024年6月29日 12:07 回复

你的答案