在 TypeScript 中处理日期:流行库概述
日期和时间的处理是 Web 开发中最常见但也最棘手的任务之一。JavaScript(以及 TypeScript)内置的 Date 对象存在诸多缺陷:可变性、不直观的 API、时区问题以及缺乏便捷的格式化方法。幸运的是,TypeScript 生态系统提供了几个强大的库来解决这些问题,并提供出色的类型支持。
在本文中,我们将介绍三个最流行的库:date-fns、Luxon 和 Day.js。您将了解它们的特点、优势、劣势,并看到在 TypeScript 中的使用示例。
1. date-fns — 模块化且函数式
date-fns 是一个基于函数式编程原则构建的库。每个函数都是一个独立的模块,允许您只导入所需的部分,从而显著减小打包体积。该库在 TypeScript 中内置了类型。
安装
npm install date-fns在 TypeScript 中的使用示例
import { format, addDays, differenceInDays, isAfter, parseISO } from 'date-fns';
// 格式化日期const today = new Date();console.log(format(today, 'yyyy-MM-dd')); // '2025-03-20'
// 添加天数const nextWeek = addDays(today, 7);console.log(format(nextWeek, 'dd.MM.yyyy')); // '27.03.2025'
// 日期差const startDate = parseISO('2025-01-01');const endDate = parseISO('2025-12-31');const daysBetween = differenceInDays(endDate, startDate);console.log(`2025 年的天数: ${daysBetween}`); // 364
// 日期比较const isFuture = isAfter(parseISO('2025-06-01'), today);console.log(`2025 年 6 月 1 日在未来吗? ${isFuture}`); // true优势
- 树摇优化 (tree-shaking) — 只导入需要的函数,减小应用体积。
- 不可变性 — 函数不修改原始对象,而是返回新对象。
- TypeScript 支持 — 开箱即用的完整类型化。
- 本地化 — 支持多种语言,包括俄语。
劣势
- 使用原生
Date对象,在处理复杂时区操作时可能不便。 - 没有内置的不可变对象支持(如 Luxon)。
2. Luxon — 强大且现代
Luxon 是由 Moment.js 的一位作者开发的库,但没有其缺点。它使用自己的不可变对象 DateTime、Duration 和 Interval,使日期处理变得直观且安全。Luxon 对时区和区域设置提供了出色的支持。
安装
npm install luxon对于 TypeScript,可能需要安装类型定义:
npm install --save-dev @types/luxon在 TypeScript 中的使用示例
import { DateTime, Duration } from 'luxon';
// 创建和格式化const now = DateTime.now();console.log(now.toFormat('yyyy-MM-dd HH:mm:ss')); // '2025-03-20 14:30:00'
// 时区处理const moscowTime = DateTime.now().setZone('Europe/Moscow');console.log(`莫斯科时间: ${moscowTime.toFormat('HH:mm')}`);
// 添加间隔const nextMonth = now.plus({ months: 1 });console.log(`一个月后: ${nextMonth.toFormat('dd.MM.yyyy')}`);
// 日期差const start = DateTime.fromISO('2025-01-01');const end = DateTime.fromISO('2025-12-31');const diff = end.diff(start, ['months', 'days']);console.log(`差值: ${diff.months} 个月和 ${diff.days} 天`);
// 处理持续时间const duration = Duration.from