在 TypeScript 中处理日期:流行库与示例

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 TypeScript 中处理日期:库概览



日期处理是 Web 开发中最常见的任务之一。在 TypeScript(和 JavaScript)中,内置的 Date 对象功能有限且 API 不便。幸运的是,有许多库可以简化日期的格式化、解析、比较和操作。本文将介绍四个流行的库:date-fns、Day.js、Luxon 和 Moment.js,并展示它们在 TypeScript 中的使用示例。



1. date-fns — 模块化且轻量



date-fns 是一个基于模块化原则构建的现代库。您只导入需要的函数,从而保持包体积最小。date-fns 开箱即用地支持 TypeScript。



安装:

npm install date-fns# 或yarn add date-fns


使用示例:

import { format, addDays, differenceInDays, parseISO } from 'date-fns';

// 格式化const today = new Date();console.log(format(today, 'yyyy-MM-dd')); // 2025-03-15

// 添加天数const future = addDays(today, 10);console.log(format(future, 'dd.MM.yyyy')); // 25.03.2025

// 日期差const start = parseISO('2025-01-01');const end = parseISO('2025-03-15');console.log(differenceInDays(end, start)); // 73

// 检查是否为周末import { isWeekend } from 'date-fns';console.log(isWeekend(new Date(2025, 2, 15))); // true (星期六)


2. Day.js — Moment.js 的轻量替代品



Day.js 是一个极简库(仅 2 kB),API 与 Moment.js 非常相似。如果您想从 Moment 迁移但减小包体积,它是理想选择。Day.js 通过类型支持 TypeScript。



安装:

npm install dayjs# 或yarn add dayjs


使用示例:

import dayjs from 'dayjs';import relativeTime from 'dayjs/plugin/relativeTime';import utc from 'dayjs/plugin/utc';

dayjs.extend(relativeTime);dayjs.extend(utc);

// 创建和格式化const now = dayjs();console.log(now.format('DD/MM/YYYY HH:mm')); // 15/03/2025 14:30

// 相对时间console.log(dayjs('2025-03-10').fromNow()); // 5 days ago

// 使用 UTCconst utcDate = dayjs.utc('2025-03-15T12:00:00Z');console.log(utcDate.local().format('HH:mm')); // 本地时间

// 操作const nextMonth = dayjs().add(1, 'month');console.log(nextMonth.format('MMMM YYYY')); // April 2025


3. Luxon — 强大且现代



Luxon 是 Moment.js 的继承者,由同一团队开发。它使用原生的 DateTime 对象,支持时区、区间和持续时间。Luxon 用 TypeScript 编写,具有出色的类型定义。



安装:

npm install luxon# 或yarn add luxon


使用示例:

import { DateTime, Interval, Duration } from 'luxon';

// 创建和格式化const dt = DateTime.now();console.log(dt.toFormat('yyyy LLL dd')); // 2025 Mar 15

// 时区const ny = DateTime.now().setZone('America/New_York');console.log(ny.toLocaleString(DateTime.DATETIME_FULL)); // March 15, 2025 at 9:30 AM EDT

// 区间const start = DateTime.fromISO('2025-01-01');const end = DateTime.fromISO('2025-03-15');const interval = Interval.fromDateTimes(start, end);console.log(interval.length('days')); // 73

// 持续时间const dur = Duration.fromObject({ hours: 5, minutes: 30 });console.log(dur.toHuman()); // 5 hours, 30 minutes

// 解析

推荐