@art-site/art-core-ts-time (英语)
在JavaScript和TypeScript中与日期,时间,和持续时间一起工作的无缝,简单公用设备.
为什么是这个模块?
为什么:
在JavaScript中与日期,时间,和持续时间一起工作是出名的容易出错和不一致的. 开发者往往需要在数字、字符串和 Date 对象,或以人类友好的方式表示当前时间,但标准API是杂乱无章和零散的.
如何解释:
该图书馆提供一套统一的公用设施,用于标准日期/时间表述之间的无功转换(number, (中文(简体) ), string, (中文(简体) ), Date以及容易的格式和列报方式(例如, formatDate, (中文(简体) ), timeAgo, (中文(简体) ), humanDurationString) (中文(简体) ). 也使得不同时间单位(秒,时,日等)之间的转换和进行"从天起"或"从正月起"等常见计算变得微不足道.
何谓: 一套综合的转换、格式化和提交日期和时间的职能,加上与时间单位和期限合作的助手.
毫秒和秒数
JavaScript date-time-as-number使用毫秒为单位. 然而,秒往往是更自然(和高效)的选择单位. 这个库通过一个强大的假设来解决了这个问题,这个假设允许您同时使用毫秒和秒:
- 日期/时间( 秒) : 任意
number < 100000000000被视为秒 - 以毫秒计的日期/时间 : 任意
number >= 100000000000被认为是毫秒
这意味着支持的秒和毫秒日期时间范围为:
- 以秒计的日期/时间 : 1970年到公元5138年在位.
- 以毫秒计的日期/时间范围 : 1973-03-03T09:46:40.000Z 到基本永恒 (ChatGPT说公元275,760
换句话说,通过作出小的牺牲 -- -- 在1970至1973年期间不能代表大于5138年或毫秒的日期/时间秒 -- -- 我们获得了无缝工作的能力,既不能代表日期/时间的共同数字,也不能考虑使用哪个数字.
安装和使用示例( 需要)
用 npm 安装 :
npm install @art-suite/art-core-ts-time
基本用途:
import {
formatDate,
toMilliseconds,
toSeconds,
toDate,
timeAgo,
humanDurationString,
firstOfDay,
firstOfMonth,
secondsPer,
} from "@art-suite/art-core-ts-time";
// Convert between types
toMilliseconds("2024-01-01"); // e.g., 1704067200000
toSeconds(new Date()); // e.g., 1704067200
toDate(1704067200000); // Date object
// Format and present
formatDate(new Date(), "yyyy-MM-dd"); // "2024-06-01"
timeAgo(new Date(Date.now() - 60000)); // "1m ago"
humanDurationString(3661); // "1h 1m 1s"
// Time calculations
firstOfDay(new Date()); // Seconds since epoch at start of today (UTC)
firstOfMonth(new Date()); // Seconds since epoch at start of this month (UTC)
// Time unit constants
secondsPer.hour; // 3600
secondsPer.day; // 86400
职能概览
转换水电费
toMilliseconds(value)- 转换 aDate,字符串,或数字到毫秒.toSeconds(value)- 转换 aDate,字符串,或数字至秒.toDate(value)- 转换字符串、数字或Date改为Date对象.
格式和列报
formatDate(value, format?, utc?)——将日期格式化为字符串,可选格式和UTC支持.timeAgo(date, options?)——人性友好"相去相去"弦(如"相去相去","相去相去"等).humanDurationString(seconds, options?)——将一个持续时间以秒为单位格式为人可读字符串(如"1h 2m 3s").niceDateString(date, now?)——友好日期字符串(如"今天","同","六月一"等).niceFullDateString(date)——完整可读的日期字符串(如"3:45pm June 1, 2024").
时间计算
firstOfHour(time)——时间刚开始的时代以来的秒数.firstOfDay(time)——自正月初一(UTC)起的秒数.firstOfWeek(time)——自一周开始(UTC,星期一)以来的秒数.firstOfMonth(time)——自正月初一起秒(UTC).firstOfYear(time)——自开元(UTC)以来的秒数.- 地语变体:
firstOfDayLocale, (中文(简体) ),firstOfWeekLocale, (中文(简体) ),firstOfMonthLocale, (中文(简体) ),firstOfYearLocale。 。 。 .
时间单位常数
secondsPer——对象映射时间单位(如:,hour, (中文(简体) ),day, (中文(简体) ),month以秒计.
API 文档参考
关于所有被输出功能及其参数的详细信息,请参见源代码内的TypeScript打字和JSDoc评论.