Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 格式化日期的程序

用于格式化日期的 JavaScript 程序

在本例中,您将学习编写一个格式化日期的 JavaScript 程序。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript if...else 语句 JavaScript 日期和时间

示例 1: 格式化日期

// program to format the date
// get current  date
let currentDate = new Date();
// get the day from the date
let day = currentDate.getDate();
// get the month from the date
// + 1 because month starts from 0
let month = currentDate.getMonth() + 1;
// get the year from the date
let year = currentDate.getFullYear();
// if day is less than 10, add 0 to make consistent format
if (day < 10) {
    day = '0' + day;
}
// if month is less than 10, add 0
if (month < 10) {
    month = '0' + month;
}
// display in various formats
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
在上面的例子中,
1. new Date() 对象给出当前日期和时间。
let currentDate = new Date();
console.log(currentDate);
// Output
// Wed Aug 26 2020 10:45:25 GMT+0545 (+0545)
2. getDate() 方法返回指定日期的日期。
let day = currentDate.getDate();
console.log(day); // 26
3. getMonth() 方法返回指定日期的月份。
let month = currentDate.getMonth() + 1;
console.log(month); // 8
4. 1 被添加到 getMonth() 方法中,因为月份从 0 开始。因此,一月是0,二月是1,依此类推。
5. getFullYear() 返回指定日期的年份。
let year = currentDate.getFullYear();
console.log(year); // 2020
然后您可以以不同的格式显示日期。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4