在JavaScript中,可以使用内置的Date对象来进行日期操作和时间戳转换。
获取当前日期和时间
可以使用new Date()
来获取当前日期和时间,返回的是当前系统时间的Date对象。例如:
let currentDate = new Date();
console.log(currentDate); // 2021-09-30T08:00:00.000Z
获取指定日期和时间
可以使用new Date(year, month, day, hour, minute, second, millisecond)
来创建指定日期和时间的Date对象。其中,year是年份(必需),month是月份(0-11),day是日(1-31),hour是小时(0-23),minute是分钟(0-59),second是秒(0-59),millisecond是毫秒(0-999)。例如:
let specifiedDate = new Date(2021, 8, 30, 10, 30, 0, 0);
console.log(specifiedDate); // 2021-09-30T02:30:00.000Z
获取日期和时间的各个部分
可以使用Date对象的各种方法来获取日期和时间的各个部分。例如:
let currentDate = new Date();
console.log(currentDate.getFullYear()); // 2021,获取年份
console.log(currentDate.getMonth()); // 8,获取月份,0表示一月,11表示十二月
console.log(currentDate.getDate()); // 30,获取日
console.log(currentDate.getHours()); // 16,获取小时
console.log(currentDate.getMinutes()); // 0,获取分钟
console.log(currentDate.getSeconds()); // 0,获取秒
console.log(currentDate.getMilliseconds()); // 0,获取毫秒
console.log(currentDate.getDay()); // 4,获取星期几,0表示星期日,6表示星期六
日期格式化
可以使用各种库或自己编写代码来对日期进行格式化。例如,使用moment.js库:
let currentDate = new Date();
let formattedDate = moment(currentDate).format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate); // 2021-09-30 16:00:00
获取当前时间戳
可以使用Date.now()
或new Date().getTime()
来获取当前时间戳,单位是毫秒。例如:
let timestamp = Date.now();
console.log(timestamp); // 1633017600000
将时间戳转换为Date对象
可以使用new Date(timestamp)
将时间戳转换为Date对象。例如:
let timestamp = 1633017600000;
let date = new Date(timestamp);
console.log(date); // 2021-09-30T08:00:00.000Z
将Date对象转换为时间戳
可以使用date.getTime()
将Date对象转换为时间戳,单位是毫秒。例如:
let date = new Date(2021, 8, 30, 10, 30, 0, 0);
let timestamp = date.getTime();
console.log(timestamp); // 1632994200000