在JavaScript中,有许多方法可以进行时间转换和操作。以下是一些常见的时间转换和操作方法:
-
创建日期对象
let now = new Date(); // 当前时间 let specificDate = new Date('2023-05-25T12:00:00Z'); // 特定时间
-
获取日期和时间的各个部分
let year = now.getFullYear(); // 年份 let month = now.getMonth(); // 月份(0-11) let day = now.getDate(); // 日期(1-31) let hours = now.getHours(); // 小时(0-23) let minutes = now.getMinutes(); // 分钟(0-59) let seconds = now.getSeconds(); // 秒(0-59) let milliseconds = now.getMilliseconds(); // 毫秒(0-999) let dayOfWeek = now.getDay(); // 星期几(0-6,0代表星期日)
-
设置日期和时间的各个部分
now.setFullYear(2024); // 设置年份 now.setMonth(11); // 设置月份(0-11) now.setDate(25); // 设置日期(1-31) now.setHours(14); // 设置小时(0-23) now.setMinutes(30); // 设置分钟(0-59) now.setSeconds(45); // 设置秒(0-59) now.setMilliseconds(500); // 设置毫秒(0-999)
-
时间字符串转换为日期对象
let dateFromString = new Date('2023-05-25T12:00:00Z');
-
日期对象转换为字符串
let dateString = now.toISOString(); // 转换为ISO 8601格式的字符串 let dateLocaleString = now.toLocaleString(); // 转换为本地时间格式的字符串 let dateLocaleDateString = now.toLocaleDateString(); // 转换为本地日期格式的字符串 let dateLocaleTimeString = now.toLocaleTimeString(); // 转换为本地时间格式的字符串
-
时间戳转换
let timestamp = now.getTime(); // 获取时间戳(毫秒数) let dateFromTimestamp = new Date(timestamp); // 通过时间戳创建日期对象
-
时间的加减
let futureDate = new Date(now); futureDate.setDate(now.getDate() + 5); // 当前日期加5天 let pastDate = new Date(now); pastDate.setHours(now.getHours() - 3); // 当前时间减3小时
-
解析时间字符串
let parsedDate = Date.parse('2023-05-25T12:00:00Z'); // 返回时间戳
-
格式化日期
let options = { year: 'numeric', month: 'long', day: 'numeric' }; let formattedDate = now.toLocaleDateString('zh-CN', options); // 格式化为中文日期字符串
-
使用第三方库(如Moment.js、Day.js)
// 使用Moment.js let momentDate = moment(); let formattedMomentDate = momentDate.format('YYYY-MM-DD HH:mm:ss'); // 使用Day.js let dayjsDate = dayjs(); let formattedDayjsDate = dayjsDate.format('YYYY-MM-DD HH:mm:ss');