npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ms-parser-lite-ts

v1.0.0

Published

Ultra-fast (<1 KB), zero-dependency human-readable time duration formatter and parser for TypeScript and Node.js.

Readme

ms-parser-lite-ts

Ultra-lightweight human-readable time duration parser and formatter (ms, s, m, h, d, w, y) in TypeScript with zero dependencies.

npm version npm downloads license bundle size sponsor


💡 Why ms-parser-lite-ts?

Parsing strings like "2 days", "15m", or "1.5h" into numeric milliseconds—and formatting milliseconds back into human-friendly strings—is common across backends, rate limiters, caching layers, and token lifespans.

  • Zero Dependencies: Pure TypeScript, tiny footprint (<700 bytes minified & gzipped).
  • Bidirectional: Includes parseMs to convert strings to numbers, and formatMs to convert numbers back to clean text.
  • Support for All Common Units: Milliseconds (ms), seconds (s, sec), minutes (m, min), hours (h, hr), days (d), weeks (w), and years (y).
  • Flexible Formatting: Supports both compact abbreviations (2d, 15m) and full English phrases (2 days, 15 minutes).
  • Compound Durations: Parses multi-segment expressions like "1h 30m" or "2d 12h" naturally.

📦 Installation

# npm
npm install ms-parser-lite-ts

# pnpm
pnpm add ms-parser-lite-ts

# yarn
yarn add ms-parser-lite-ts

# bun
bun add ms-parser-lite-ts

🚀 Quick Start

import { parseMs, formatMs } from 'ms-parser-lite-ts';

// 1. Parsing human strings to milliseconds
parseMs('2 days');       // => 172800000
parseMs('15m');          // => 900000
parseMs('1.5h');         // => 5400000
parseMs('2.5s');         // => 2500
parseMs('500ms');        // => 500
parseMs('1h 30m');       // => 5400000 + 1800000 = 7200000

// 2. Formatting milliseconds to human strings
formatMs(60000);                    // => '1m'
formatMs(60000, { long: true });    // => '1 minute'
formatMs(172800000, { long: true });// => '2 days'
formatMs(5400000);                  // => '1.5h'

🛠️ Real-World Examples

1. Redis / Cache TTL Configuration

Allow developers to configure cache durations using intuitive human strings instead of raw integers:

import { parseMs } from 'ms-parser-lite-ts';

export async function setCache(key: string, data: any, ttlString = '1 hour') {
  const ttlMilliseconds = parseMs(ttlString);
  const ttlSeconds = Math.round(ttlMilliseconds / 1000);
  
  await redis.set(key, JSON.stringify(data), 'EX', ttlSeconds);
}

// Clear, declarative TTLs!
await setCache('user:101', profileData, '15m');
await setCache('daily:stats', statsData, '1d');

2. Cookie maxAge & JWT Expiry Calculations

import { parseMs } from 'ms-parser-lite-ts';

export function createSessionCookie(res: any, token: string, expiry = '7 days') {
  const maxAgeMs = parseMs(expiry);

  res.setHeader('Set-Cookie', `session=${token}; Max-Age=${Math.floor(maxAgeMs / 1000)}; HttpOnly; Secure; SameSite=Strict; Path=/`);
}

3. Rate Limiter Window Durations

import { parseMs, formatMs } from 'ms-parser-lite-ts';

export function createRateLimiter(options: { max: number; window: string }) {
  const windowMs = parseMs(options.window);
  const prettyWindow = formatMs(windowMs, { long: true });

  console.log(`Rate limit initialized: ${options.max} requests per ${prettyWindow}`);
  return { max: options.max, windowMs };
}

const apiLimiter = createRateLimiter({ max: 100, window: '15 minutes' });

4. Background Job Scheduling / Polling Intervals

import { parseMs } from 'ms-parser-lite-ts';

export function scheduleCronJob(taskName: string, interval: string, handler: () => void) {
  const intervalMs = parseMs(interval);
  console.log(`Starting ${taskName} every ${interval} (${intervalMs}ms)`);
  return setInterval(handler, intervalMs);
}

const cleanupTimer = scheduleCronJob('Database Cleaner', '30m', () => {
  // run cleanup
});

📖 API Reference

parseMs(input)

Parses a duration string into the total number of milliseconds.

  • Parameters: input (string)
  • Returns: number (milliseconds)
  • Throws: Error if the string cannot be parsed into a valid duration.

Supported units:

  • ms, msec, millisecond, milliseconds
  • s, sec, second, seconds
  • m, min, minute, minutes
  • h, hr, hour, hours
  • d, day, days
  • w, wk, week, weeks
  • y, yr, year, years

formatMs(ms, options?)

Formats a numeric millisecond value into a concise human-readable duration string.

  • Parameters:
    • ms (number): Duration in milliseconds.
    • options (FormatMsOptions, optional): Configuration options.
  • Returns: string (formatted time duration).

Options (FormatMsOptions):

| Option | Type | Default | Description | |---|---|---|---| | long | boolean | false | When true, formats with full unit names (e.g. '2 days' instead of '2d') |


🏷️ TypeScript Interfaces

export interface FormatMsOptions {
  /**
   * Whether to format with verbose unit names (e.g. "2 hours" vs "2h").
   * @default false
   */
  long?: boolean;
}

🧪 Testing

Every release is tested with 100% test coverage using Vitest:

npm test

💖 Support the Project

If ms-parser-lite-ts saved you from calculating milliseconds by hand, please consider sponsoring:

👉 Sponsor @Piratha97 on GitHub Sponsors


📄 License

MIT © 2026 Pirapaakaran Pirathapan