// 获取当前日期和时间
let now = new Date();
console.log(now); // 输出类似: 2023-10-05T14:48:32.123Z
// 创建特定日期的对象
let birthday = new Date('2000-01-01');
console.log(birthday); // 输出: 2000-01-01T00:00:00.000Z
// 获取年份、月份、日期等信息
let year = now.getFullYear(); // 获取年份
let month = now.getMonth() + 1; // 获取月份 (注意: getMonth() 返回的是0-11,所以要加1)
let date = now.getDate(); // 获取日期
let day = now.getDay(); // 获取星期几 (0 表示星期天, 6 表示星期六)
let hours = now.getHours(); // 获取小时
let minutes = now.getMinutes(); // 获取分钟
let seconds = now.getSeconds(); // 获取秒数
console.log(`当前时间是: ${year}-${month}-${date} ${hours}:${minutes}:${seconds}`);
// 设置日期和时间
let futureDate = new Date();
futureDate.setFullYear(2025);
futureDate.setMonth(11); // 11 表示12月
futureDate.setDate(25);
futureDate.setHours(23);
futureDate.setMinutes(59);
futureDate.setSeconds(59);
console.log(futureDate); // 输出: 2025-12-25T23:59:59.000Z
// 计算两个日期之间的差异
let start = new Date('2023-01-01');
let end = new Date('2023-12-31');
let diffTime = Math.abs(end - start); // 毫秒差
let diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); // 天数差
console.log(`从 ${start} 到 ${end} 相差 ${diffDays} 天`);
new Date() 创建一个表示当前日期和时间的对象,也可以通过传递字符串或时间戳来创建特定日期的对象。getFullYear()、getMonth()、getDate() 等方法可以获取年份、月份、日期等信息。注意 getMonth() 返回的月份是从0开始的(即0表示1月)。setFullYear()、setMonth()、setDate() 等方法可以修改日期对象中的具体时间。Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站