// 创建一个新的 Date 对象,表示当前日期和时间
let currentDate = new Date();
console.log(currentDate); // 输出类似:2023-10-05T00:00:00.000Z
// 创建一个指定日期的 Date 对象
let specificDate = new Date('2023-10-01');
console.log(specificDate); // 输出:2023-10-01T00:00:00.000Z
// 获取当前日期的年份、月份(从 0 开始)、日期、小时、分钟、秒数和毫秒数
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1; // 注意:月份是从 0 开始的
let date = currentDate.getDate();
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();
let milliseconds = currentDate.getMilliseconds();
console.log(`当前时间是:${year}-${month}-${date} ${hours}:${minutes}:${seconds}.${milliseconds}`);
// 设置日期和时间
currentDate.setFullYear(2024);
currentDate.setMonth(11); // 11 表示 12 月,因为月份是从 0 开始的
currentDate.setDate(25);
currentDate.setHours(23);
currentDate.setMinutes(59);
currentDate.setSeconds(59);
currentDate.setMilliseconds(999);
console.log(currentDate); // 输出:2024-12-25T23:59:59.999Z
// 将 Date 对象转换为字符串
let dateString = currentDate.toString();
console.log(dateString); // 输出:Wed Dec 25 2024 23:59:59 GMT+0000 (Coordinated Universal Time)
// 获取时间戳(自 1970 年 1 月 1 日 00:00:00 UTC 到现在的毫秒数)
let timestamp = currentDate.getTime();
console.log(timestamp); // 输出:1703539199999
// 根据时间戳创建 Date 对象
let dateFromTimestamp = new Date(timestamp);
console.log(dateFromTimestamp); // 输出:Wed Dec 25 2024 23:59:59 GMT+0000 (Coordinated Universal Time)
new Date() 创建一个表示当前日期和时间的对象,或者通过传递日期字符串或时间戳来创建特定日期的对象。getFullYear()、getMonth()、getDate() 等方法用于获取年份、月份、日期等信息。注意月份是从 0 开始的(0 表示 1 月)。setFullYear()、setMonth()、setDate() 等方法用于修改日期对象中的年份、月份、日期等。toString() 方法将 Date 对象转换为字符串格式。getTime() 方法返回自 1970 年 1 月 1 日 00:00:00 UTC 到现在的毫秒数。new Date() 来创建对应的 Date 对象。上一篇:js datetime
下一篇:js math.random()
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站