JavaScript 编写日期格式化程序
要理解这个示例,你应该具备以下 JavaScript 编程 主题的知识:
示例 1:格式化日期
// 程序格式化日期
// 获取当前日期
let currentDate = new Date();
// 从日期获取日
let day = currentDate.getDate();
// 从日期获取月份
// +1 是因为月份从0开始
let month = currentDate.getMonth() + 1;
// 从日期获取年份
let year = currentDate.getFullYear();
// 如果日期小于10,前面加0以保持一致的格式
if (day < 10) {
day = "0" + day;
}
// 如果月份小于10,前面加0
if (month < 10) {
month = "0" + month;
}
// 以不同格式显示
const formattedDate1 = month + "/" + day + "/" + year;
console.log(formattedDate1);
const formattedDate2 = month + "-" + day + "-" + year;
console.log(formattedDate2);
const formattedDate3 = day + "-" + month + "-" + year;
console.log(formattedDate3);
const formattedDate4 = day + "/" + month + "/" + year;
console.log(formattedDate4);
输出
08/26/2020
08-26-2020
26-08-2020
26/08/2020
在上述示例中,
new Date()
对象提供了当前日期和时间。
let currentDate = new Date();
console.log(currentDate);
// 输出
// 2020年8月26日 星期三 10:45:25 GMT+0545 (+0545)
getDate()
方法从指定日期返回日。
let day = currentDate.getDate();
console.log(day); // 26
getMonth()
方法从指定日期返回月份。
let month = currentDate.getMonth() + 1;
console.log(month); // 8
-
getMonth()
方法加上 1 是因为月份从 0 开始。因此,一月是 0,二月是 1,依此类推。 -
getFullYear()
方法从指定日期返回年份。
let year = currentDate.getFullYear();
console.log(year); // 2020
然后你可以以不同的格式展示日期。