kaze-ts-date-utils
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

ts-date-utils

A simple and flexible TypeScript date formatting utility.

轻量、简洁的 TypeScript 日期时间格式化工具,支持自定义模板格式,适用于各种 Node.js 和浏览器项目。


✨ 特性

  • 支持自定义格式(YYYY-MM-DD HH:mm:ss
  • 支持时间戳格式化
  • 支持当前时间快速获取
  • 支持字符串解析成 Date
  • TypeScript 全类型提示
  • 零依赖,超轻量

📦 安装

npm install ts-date-utils

或使用 yarn:

yarn add ts-date-utils



⸻

🚀 快速开始

import { formatDate, formatTimestamp, now, parseDateString, isValidDate } from 'ts-date-utils';

// 获取当前时间
console.log(now()); 
// => 2025-04-29 19:45:00

// 格式化时间戳
console.log(formatTimestamp(1714387200000, 'YYYY/MM/DD')); 
// => 2025/04/29

// 格式化 Date 对象
const date = new Date('2025-05-01T12:00:00');
console.log(formatDate(date, 'YYYY年MM月DD日 HH:mm')); 
// => 2025年05月01日 12:00

// 解析字符串为 Date 对象
const parsed = parseDateString('2025-05-01 12:00:00');
console.log(parsed.toISOString());

// 校验是否为合法 Date
console.log(isValidDate(new Date())); 
// => true
console.log(isValidDate('hello')); 
// => false



⸻

🛠️ API 文档

formatDate(date: Date, format?: string): string

格式化一个 Date 对象为指定字符串。
	•	date:要格式化的日期对象
	•	format:格式模板,默认 'YYYY-MM-DD HH:mm:ss'

支持的模板字段:

字段	含义
YYYY	年份
MM	月(两位数)
DD	日(两位数)
HH	小时(两位数)
mm	分钟(两位数)
ss	秒钟(两位数)



⸻

formatTimestamp(timestamp: number, format?: string): string

格式化时间戳(毫秒数)为指定格式。

⸻

now(format?: string): string

获取当前时间的格式化字符串。

⸻

parseDateString(dateString: string): Date

将日期字符串解析成 Date 对象。
支持格式如:2025-04-29 18:00:00,2025/04/29 等。

⸻

isValidDate(date: unknown): boolean

判断传入参数是否为有效的 Date 对象。


Package Sidebar

Install

npm i kaze-ts-date-utils

Weekly Downloads

4

Version

1.0.0

License

MIT

Unpacked Size

5.73 kB

Total Files

5

Last publish

Collaborators

  • kaze_fg