在 TypeScript 中处理日期和时间:从基础到进阶技巧
日期和时间管理是 Web 开发中的关键任务之一。无论是显示发布时间、计算截止日期还是与服务器同步数据,TypeScript 都提供了强大的工具来处理时间戳。在本文中,我们将深入探讨日期处理的所有方面:从创建 Date 对象到时区复杂操作和格式化。
1. TypeScript 中 Date 对象的基础知识
在 TypeScript 中,与 JavaScript 一样,内置的 Date 对象负责处理日期。得益于严格的类型系统,TypeScript 有助于避免在传递不正确数据时出现错误。
创建 Date 对象
有几种方法可以创建日期实例:
// 当前日期和时间const now: Date = new Date();console.log(now); // Tue Oct 24 2023 14:30:00 GMT+0300
// 根据毫秒数(Unix 时间戳)const fromTimestamp: Date = new Date(1698153000000);
// 根据字符串(ISO 8601)const fromString: Date = new Date("2023-10-24T12:00:00Z");
// 根据组件(年、月、日、时、分、秒)const customDate: Date = new Date(2023, 9, 24, 14, 30, 0); // 月份从 0 到 11!重要提示: JavaScript/TypeScript 中的月份从 0 开始编号(一月为 0,十二月为 11)。这是常见的错误来源。
获取日期组件
使用 getter 方法提取日期的各个部分:
const date: Date = new Date();const year: number = date.getFullYear(); // 2023const month: number = date.getMonth(); // 9(十月)const day: number = date.getDate(); // 24const hours: number = date.getHours(); // 14const minutes: number = date.getMinutes(); // 30const seconds: number = date.getSeconds(); // 0const dayOfWeek: number = date.getDay(); // 2(星期二,0 为星期日)2. 日期格式化与输出
标准的 Date.toString() 输出通常不适合用户界面。让我们看看主要的格式化方法。
内置格式化方法
toDateString()— "Tue Oct 24 2023"toLocaleDateString()— 本地化日期(例如,俄罗斯为 "24.10.2023")toISOString()— ISO 格式字符串("2023-10-24T11:30:00.000Z")
const date: Date = new Date();console.log(date.toLocaleDateString('zh-CN')); // 2023/10/24console.log(date.toLocaleTimeString('zh-CN')); // 14:30:00使用 Intl.DateTimeFormat 进行自定义格式化
要获得更灵活的控制,请使用 Intl.DateTimeFormat:
const date: Date = new Date();const formatter = new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long', hour: '2-digit', minute: '2-digit'});console.log(formatter.format(date)); // "星期二, 2023年10月24日 14:30"date-fns 库
对于复杂任务,建议使用 date-fns 库。它轻量级且对 TypeScript 有出色的支持:
import { format, addDays, isWeekend } from 'date-fns';import { zhCN } from 'date-fns/locale';
const date: Date = new Date();console.log(format(date, 'dd.MM.yyyy', { locale: zhCN })); // "24.10.2023"console.log(format(date, 'HH:mm:ss')); // "14:30:00"console.log(isWeekend(date)); // false3. 日期操作:加法、减法和比较
修改日期
最简单的方法是使用 setter 方法:
const date: Date = new Date();date.setFullYear(2024);date.setMonth(11); // 十二月date.setDate(31);console.log(date); // "Tue Dec 31 2024 14:30