// 获取当前日期和时间
let now = new Date();
console.log(now); // 输出类似: 2023-10-05T14:48:32.123Z
// 创建特定日期和时间的对象
let specificDate = new Date(2023, 9, 5, 14, 30, 0); // 注意月份是从0开始计数的,所以9表示10月
console.log(specificDate); // 输出类似: 2023-10-05T07:30:00.000Z
// 格式化日期和时间
let year = now.getFullYear();
let month = now.getMonth() + 1; // 月份从0开始,需要加1
let day = now.getDate();
let hours = now.getHours();
let minutes = now.getMinutes();
let seconds = now.getSeconds();
console.log(`${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`);
// 输出类似: 2023-10-05 14:48:32
// 将日期字符串转换为 Date 对象
let dateString = '2023-10-05T14:48:32.123Z';
let dateFromStr = new Date(dateString);
console.log(dateFromStr); // 输出类似: 2023-10-05T14:48:32.123Z
new Date() 可以创建一个表示当前日期和时间的 Date 对象。Date 对象。注意月份是从0开始计数的。getFullYear()、getMonth()、getDate() 等方法提取日期和时间的各个部分,并使用模板字符串和 padStart() 方法进行格式化。new Date(dateString) 将 ISO 格式的日期字符串转换为 Date 对象。上一篇:js date 加一天
下一篇:js math.random()
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站