JavaScript 中将完整日期转换为短日期
使用 toLocaleDateString()
方法将完整日期转换为短日期。 该方法将语言环境和选项对象作为参数,并根据提供的语言环境和选项返回表示日期的字符串。
const date = new Date('2022-09-24');
// 👇️ "09/24/2022"
console.log(
date.toLocaleDateString('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}),
);
toLocaleDateString()
方法根据提供的参数返回日期的字符串表示形式。
我们传递给该方法的两个参数是:
- locales - 带有 BCP 47 语言标记的字符串或此类字符串的数组。 我们可以使用任何可用的语言环境,例如 墨西哥为 es-MX,加拿大为 en-CA。 如果您需要有关此参数的更多信息,请查看 MDN 文档。
- options - 我们可以在其中调整格式样式。
上面的示例使用 en-US
区域设置获取短日期。 但是,我们可以通过为 locales 参数传递一个空数组来使用访问者的默认区域设置。
// 👇️ use visitor's default locale
console.log(
date.toLocaleDateString([], {
year: 'numeric',
month: '2-digit',
day: '2-digit',
}),
);
上面的示例使用了访问者的默认语言环境。 换句话说,短日期的格式会根据用户的首选语言环境而有所不同。
年份属性可以设置为:
- 数字 - 例如 2022年
- 2 位数 - 例如 22
month 属性可以设置为:
- 数字 - 例如 9
- 2 位数 - 例如 09
- long - 例如 九月
- short - 例如 九月
- narrow - 例如 S
日属性可以设置为:
- 数字 - 例如 4个
- 2 位数 - 例如 04
根据我们传递给函数的语言环境,短日期的格式可能会有所不同。
如果日期或月份的值小于 10,则某些语言环境会添加前导零,而其他语言环境则不会。
将月份和日期属性设置为 2 位数字使我们能够始终产生一致的结果。
如果要显示工作日的名称,还可以设置 weekday 属性。
// 👇️ "Sat, 09/24/2022"
console.log(
date.toLocaleDateString('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
weekday: 'short',
}),
);
weekday
属性可以设置为:
- long - 例如 周四
- short - 例如 星期四
- narrow - 例如 吨
当月份使用窄格式时,对于某些语言环境,两个月可能具有相同的窄格式,例如 七月和六月都用J
表示。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。