在 JavaScript 中更改日期格式
确定当前时间/时刻是每个应用程序的重要部分。JavaScript 支持表示单个时间点的 Date
对象。日期对象包含一个数字,表示自 UTC 1970 年 1 月 1 日以来的毫秒数,也称为自 Unix 纪元以来的毫秒数。JavaScript 提供了多种方法来获取多种格式的日期。
在 JavaScript 中使用 Date()
更改日期格式
这是一个内置于 JavaScript 的函数,用于返回格式化的日期字符串。当调用 new Date()
时,它充当构造函数并返回 Date 对象而不是格式化的字符串。它还提供了各种静态方法,如
Date.now()
Date.parse()
Date.UTC()
Date 对象还支持实例方法,例如
Date.prototype.getDate()
:此方法将根据本地时间返回给定日期的 1-31 范围内的月份中的第几天。Date.prototype.getMonth()
:此方法将根据本地时间返回给定日期的 0-11 范围内的月份。月份将从 0 开始。Date.prototype.getYear()
:此方法将根据本地时间返回给定日期的年份。它通常返回 2-3 位数字的年份。Date.prototype.getFullYear()
:此方法将根据当地时间返回给定日期的 4 位数年份的 4 位数年份。
JavaScript 中 Date()
的语法
Date();
示例代码:
const today = new Date();
const month = [
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'
];
const str =
today.getDate() + ' ' + month[today.getMonth()] + ' ' + today.getFullYear();
console.log(str);
输出:
18 November 2021
上面的内置 Date 对象允许你更改日期格式以满足你的需要。你还可以使用像 DateJS
这样的外部库。
在 JavaScript 中使用 DateJS
更改日期格式
JavaScript 有一个名为 DateJS
的开源日期库,用于格式化、解析和处理。在此处了解如何导入 DateJS
。
DateJS 中 Date.parse()
的语法
Date.parse($string);
Date.parse()
的参数
$string
:这是一个强制性参数。此字段接受任何日期字符串,例如today
、tomorrow
、last Sunday
、July 4th
、t + 3d
等。有关更多信息,请参阅官方文档。
示例代码:
const parsedDate = Date.parse('tomorrow');
console.log(parsedDate);
输出:
Fri Nov 19 2021
DateJS 中 Date.toString()
的语法
Date.parse($string);
Date.toString()
的参数
$string
:它是一个可选参数。此字段接受任何日期字符串,如M/d/yyyy
、d-MMM-yyyy
、HH:mm
、MMMM dS, yyyy
等。默认的原生 JavaScriptDate.toString()
函数如果没有提供格式,将被调用。
示例代码:
const parsedDate = Date.today().toString('MMMM dS, yyyy');
console.log(parsedDate);
输出:
November 18th, 2021
相关文章
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
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。