Node.js中操作日期主要依赖内置的Date对象,同时也可以使用成熟的第三方库来简化复杂场景下的日期处理工作,下面将从基础到进阶逐步介绍相关实现方式。
一、内置Date对象基础操作
Node.js继承了JavaScript的Date对象,无需额外安装依赖就可以直接使用,以下是常见的基础操作示例。
1. 获取当前时间
直接实例化Date对象不传入参数,就可以得到当前的日期时间对象:
// 获取当前时间 const now = new Date(); console.log(now); // 输出当前时间的Date对象,包含年月日时分秒毫秒等信息
2. 创建指定日期
Date对象支持多种参数形式来创建指定日期,常见的方式如下:
// 传入日期字符串创建
const date1 = new Date('2024-05-20 12:30:00');
// 传入时间戳(毫秒)创建
const date2 = new Date(1716180600000);
// 传入年、月、日、时、分、秒、毫秒创建,注意月份从0开始计数
const date3 = new Date(2024, 4, 20, 12, 30, 0, 0); // 对应2024年5月20日12点30分
3. 获取日期各组成部分
Date对象提供了多个get方法,可以获取日期的年、月、日、时、分、秒等信息:
const date = new Date(); const year = date.getFullYear(); // 获取四位年份 const month = date.getMonth() + 1; // 获取月份,需要加1才是实际月份 const day = date.getDate(); // 获取日期中的日 const hours = date.getHours(); // 获取小时 const minutes = date.getMinutes(); // 获取分钟 const seconds = date.getSeconds(); // 获取秒 const milliseconds = date.getMilliseconds(); // 获取毫秒 const timestamp = date.getTime(); // 获取时间戳(毫秒数)
4. 日期格式化
内置Date对象没有直接的格式化方法,需要手动拼接字符串来实现常见的格式化需求:
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const now = new Date();
console.log(formatDate(now)); // 输出格式如 2024-05-20 12:30:00
5. 日期计算
日期计算可以通过修改时间戳来实现,比如计算3天后的时间:
const now = new Date(); const threeDaysLater = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000); console.log(formatDate(threeDaysLater)); // 输出3天后的格式化时间
二、使用第三方库简化操作
当需要处理复杂的时区转换、国际化日期、更复杂的格式化需求时,内置Date对象的使用会比较繁琐,这时候可以使用成熟的第三方库,最常用的是dayjs和moment.js。
1. dayjs库使用
dayjs是一个轻量级的日期处理库,API设计和moment.js类似,体积很小,适合大多数场景使用。首先需要安装依赖:
npm install dayjs
基础使用示例:
const dayjs = require('dayjs');
// 获取当前时间并格式化
const now = dayjs();
console.log(now.format('YYYY-MM-DD HH:mm:ss')); // 直接调用format方法格式化
// 日期计算
const threeDaysLater = now.add(3, 'day');
console.log(threeDaysLater.format('YYYY-MM-DD HH:mm:ss'));
// 解析指定日期字符串
const date = dayjs('2024-05-20 12:30:00');
console.log(date.format('YYYY年MM月DD日 HH时mm分ss秒'));
// 计算时间差(单位毫秒)
const diff = dayjs('2024-05-23').diff(dayjs('2024-05-20'), 'day');
console.log(diff); // 输出3,表示相差3天
2. moment.js库使用
moment.js是老牌的日期处理库,功能非常全面,但是体积相对较大,目前官方已经停止维护,推荐新项目优先使用dayjs。安装方式:
npm install moment
基础使用示例:
const moment = require('moment');
// 当前时间格式化
console.log(moment().format('YYYY-MM-DD HH:mm:ss'));
// 日期计算
console.log(moment().add(3, 'days').format('YYYY-MM-DD HH:mm:ss'));
// 解析日期字符串
console.log(moment('2024-05-20 12:30:00').format('YYYY/MM/DD HH:mm'));
三、时区处理注意事项
内置Date对象获取的是当前运行环境的本地时间,如果需要处理特定时区的时间,比如UTC时间,可以使用对应的方法:
const now = new Date();
// 获取UTC时间的年、月、日等信息
const utcYear = now.getUTCFullYear();
const utcMonth = now.getUTCMonth() + 1;
const utcDay = now.getUTCDate();
console.log(`UTC时间:${utcYear}-${utcMonth}-${utcDay}`);
// 使用dayjs处理时区,需要安装dayjs的时区插件
const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');
dayjs.extend(utc);
dayjs.extend(timezone);
// 转换为上海时区时间
console.log(dayjs().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss'));
四、常见场景示例
以下是两个实际开发中常见的日期操作场景示例:
1. 判断某个日期是否在当前日期之前
function isBeforeNow(dateStr) {
const targetDate = new Date(dateStr);
const now = new Date();
return targetDate.getTime() < now.getTime();
}
console.log(isBeforeNow('2024-05-19')); // 如果当前时间在2024-05-19之后,返回true
2. 获取本月第一天和最后一天的日期
function getMonthStartAndEnd() {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth();
// 本月第一天
const start = new Date(year, month, 1);
// 本月最后一天,下个月第一天减1毫秒
const end = new Date(year, month + 1, 1, 0, 0, 0, -1);
return {
start: formatDate(start),
end: formatDate(end)
};
}
console.log(getMonthStartAndEnd());
| 操作方式 | 优势 | 劣势 |
|---|---|---|
| 内置Date对象 | 无需额外依赖,原生支持 | 格式化、复杂计算需要手动实现,时区处理繁琐 |
| dayjs库 | 轻量,API简洁,支持链式调用,满足大部分场景 | 部分高级功能需要额外安装插件 |
| moment.js库 | 功能全面,生态成熟 | 体积大,官方已停止维护 |