// 创建一个新的 Date 对象,表示当前日期和时间
let currentDate = new Date();
console.log(currentDate); // 输出当前日期和时间
// 创建一个指定日期的 Date 对象
let specifiedDate = new Date(2023, 9, 15, 10, 30, 0); // 注意:月份是从0开始计数的,所以9表示10月
console.log(specifiedDate); // 输出指定的日期和时间
// 获取当前日期的年份、月份、日等信息
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1; // 月份从0开始,所以需要加1
let day = currentDate.getDate();
console.log(`今天的日期是: ${year}-${month}-${day}`);
// 格式化日期为字符串
let formattedDate = currentDate.toDateString();
console.log(formattedDate); // 输出类似 "Fri Oct 13 2023" 的格式
// 计算两个日期之间的差值(以天为单位)
let date1 = new Date('2023-10-01');
let date2 = new Date('2023-10-15');
let diffTime = Math.abs(date2 - date1);
let diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log(`两个日期相差 ${diffDays} 天`);
new Date()
可以创建一个表示当前日期和时间的对象。你也可以通过传递参数来创建特定日期的对象。getFullYear()
、getMonth()
、getDate()
等方法来获取日期的具体信息。toDateString()
方法可以将日期格式化为易读的字符串。Date
对象,可以得到它们之间的时间差(以毫秒为单位),再将其转换为天数。上一篇:javascript for
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站