New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

timelong

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

timelong

时间长度转换工具

latest
npmnpm
Version
1.5.6
Version published
Maintainers
1
Created
Source

简体中文 | English

badge badge badge badge

简介

1h2m3s4ms这种格式的字符串转为指定单位的时长

timelong.ms1h2m3s4ms => 3723004 (ms)
timelong.s1h2m3s4ms => 3723.004 (s)

使用

import timelong from "timelong";

console.log(timelong.ms1d);
const timelong = require('timelong').default;

console.log(timelong.ms1d)

属性名第一段是单位:

单位含义
w星期
d
h小时
m分钟
s
ms毫秒

后面是具体的时间长度,数字后面跟的具体单位: 1d4m 表示1天4分钟。

timelong.m1d4m会换算成具体分钟数24*60+4=1444

也可以用中文,但不能中英文混用

中文单位有:

星期、周、天、日、小时、时、分钟、分、秒、毫秒

例如:

timelong.时1天

背景

代码中经常会有定义时长的常量,例如:

// axios默认超时时间
export const AXIOS_TIMEOUT_DEFAULT = 5000; // ms

简单的还好,还有稍微需要计算的需要在脑袋里过一遍,例如:

export const TASK_TIMEOUT_PERIOD = 20 * 60 * 1000; // ms

时间单位有可能是分钟、秒等非毫秒数,如果代码里不写注释和毫秒数的时间放在一起,可能会让人感到疑惑,例如:

// redis 过期时间
export const REDIS_EXPIRE_TIME = 7 * 24 * 60 * 60; // s

如果有一个工具能按照一定格式自动生成想要的时长,我们就能偷点懒了,可读性也强些。

上面的例子就会变成

export const AXIOS_TIMEOUT_DEFAULT = timelong.ms5s;
export const TASK_TIMEOUT_PERIOD = timelong.ms20m;
export const REDIS_EXPIRE_TIME = timelong.s7d;

示例

expect(timelong.ms1ms).toBe(1);
expect(timelong.ms1s).toBe(1 * 1000);
expect(timelong.ms1m).toBe(1 * 60 * 1000);
expect(timelong.ms1h).toBe(1 * 60 * 60 * 1000);
expect(timelong.ms1d).toBe(1 * 24 * 60 * 60 * 1000);
expect(timelong.ms1w).toBe(1 * 7 * 24 * 60 * 60 * 1000);
expect(timelong.ms12w34d56h78m9s10ms).toBe(
    12 * timelong.ms1w +
    34 * timelong.ms1d +
    56 * timelong.ms1h +
    78 * timelong.ms1m +
    9 * timelong.ms1s +
    10
);
expect(timelong.m1ms).toBeCloseTo(1 / 1000 / 60);
expect(timelong.m1s).toBeCloseTo(1 / 60);
expect(timelong.m1m).toBe(1);
expect(timelong.m1h).toBe(1 * 60);
expect(timelong.m1d).toBe(1 * 24 * 60);
expect(timelong.m1w).toBe(1 * 7 * 24 * 60);
expect(timelong.m12w34d56h78m9s10ms).toBeCloseTo(
    12 * timelong.m1w +
    34 * timelong.m1d +
    56 * timelong.m1h +
    78 * timelong.m1m +
    9 * timelong.m1s +
    10 * timelong.m1ms
);
expect(timelong.时1日).toBe(1 * 24);
expect(timelong.小时1日).toBe(1 * 24);
expect(timelong.时1天).toBe(1 * 24);
expect(timelong.小时1天).toBe(1 * 24);

以此类推

实现原理

Proxy解析属性名为具体的单位、星期数、天数、小时数、分数、秒数和毫秒数再累加相除

Keywords

time

FAQs

Package last updated on 24 Jun 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts