### Install ms package Source: https://github.com/vercel/ms/blob/main/README.md Instructions for installing the 'ms' package using various package managers like npm, yarn, pnpm, deno, and bun. This allows you to include the utility in your project for time conversions. ```bash npm install ms yarn add ms pnpm add ms denp add npm:ms bun add ms ``` -------------------------------- ### Parse Time Units with MS Library (TypeScript) Source: https://context7.com/vercel/ms/llms.txt Demonstrates parsing various time units like milliseconds, seconds, minutes, hours, days, weeks, months, and years using the 'ms' library in TypeScript. Shows support for aliases, case-insensitivity, and flexible spacing between numbers and units. Assumes the 'ms' library is installed. ```typescript import { ms, parse } from 'ms'; // Milliseconds: milliseconds, millisecond, msecs, msec, ms parse('100ms'); // 100 parse('100 milliseconds'); // 100 parse('100msecs'); // 100 // Seconds: seconds, second, secs, sec, s parse('30s'); // 30000 parse('30 seconds'); // 30000 parse('30secs'); // 30000 // Minutes: minutes, minute, mins, min, m parse('5m'); // 300000 parse('5 minutes'); // 300000 parse('5mins'); // 300000 // Hours: hours, hour, hrs, hr, h parse('2h'); // 7200000 parse('2 hours'); // 7200000 parse('2hrs'); // 7200000 // Days: days, day, d parse('7d'); // 604800000 parse('7 days'); // 604800000 // Weeks: weeks, week, w parse('2w'); // 1209600000 parse('2 weeks'); // 1209600000 // Months: months, month, mo (1 month = 30.4375 days) parse('1mo'); // 2629800000 parse('1 month'); // 2629800000 // Years: years, year, yrs, yr, y (1 year = 365.25 days) parse('1y'); // 31557600000 parse('1 year'); // 31557600000 // Case insensitivity parse('5 MINUTES'); // 300000 parse('2 Hours'); // 7200000 parse('1 YEAR'); // 31557600000 // With or without space parse('10minutes'); // 600000 parse('10 minutes'); // 600000 // Decimal values with any unit parse('1.5h'); // 5400000 parse('2.5 days'); // 216000000 parse('.5y'); // 15778800000 ``` -------------------------------- ### TypeScript enhanced type safety with StringValue Source: https://github.com/vercel/ms/blob/main/README.md Demonstrates using the exported `StringValue` type from 'ms' to ensure that only valid time strings are passed to the `ms` function. This provides compile-time safety against invalid inputs. Includes examples of direct usage and type assertion. ```typescript import { ms, type StringValue } from 'ms'; // Using the exported type directly. function example(value: StringValue) { ms(value); } example('1 h'); // Valid // example('invalid string'); // This would cause a TypeScript error // Type assertion with the exported type. function exampleWithAssertion(value: string) { try { ms(value as StringValue); } catch (error: Error) { console.error(error); } } exampleWithAssertion('any value'); // This might still throw a runtime error if the value is invalid. ``` -------------------------------- ### Import parse and format functions separately from ms Source: https://github.com/vercel/ms/blob/main/README.md Demonstrates how to import and use the `parse` and `format` functions individually from the 'ms' package. `parse` converts time strings to milliseconds, while `format` converts milliseconds to time strings. ```typescript import { parse, format } from 'ms'; parse('1h'); // 3600000 format(2000); // "2s" ``` -------------------------------- ### Edge Runtime Compatibility with ms Source: https://github.com/vercel/ms/blob/main/README.md Shows how to integrate the `ms` package within an Edge Runtime environment, such as Vercel Edge Functions. This allows for dynamic time difference calculations and display in serverless functions. ```typescript // Next.js (pages/api/edge.js) (npm i next@canary) // Other frameworks (api/edge.js) (npm i -g vercel@canary) import { ms } from 'ms'; const start = Date.now(); export default (req) => { return new Response(`Alive since ${ms(Date.now() - start)}`); }; export const config = { runtime: 'experimental-edge', }; ``` -------------------------------- ### Convert milliseconds to time strings (ms) Source: https://github.com/vercel/ms/blob/main/README.md Converts millisecond values into their string representation with appropriate units. Supports converting from milliseconds to shorthand units (e.g., '1m') or long-form units (e.g., '1 minute'). Handles positive, negative, and nested millisecond conversions. ```typescript import ms from 'ms'; // Convert to shorthand string ms(60000); // "1m" ms(2 * 60000); // "2m" ms(-3 * 60000); // "-3m" ms(ms('10 hours')); // "10h" // Convert to long-form string ms(60000, { long: true }); // "1 minute" ms(2 * 60000, { long: true }); // "2 minutes" ms(-3 * 60000, { long: true }); // "-3 minutes" ms(ms('10 hours'), { long: true }); // "10 hours" ``` -------------------------------- ### ms: Convert Time Strings to Milliseconds and Vice Versa Source: https://context7.com/vercel/ms/llms.txt The main `ms` function acts as a bidirectional converter. When given a time string, it returns the equivalent milliseconds. When given a number, it returns a human-readable time string. It supports various units, negative values, and an option for long-form output. ```typescript import { ms } from 'ms'; // Parse time strings to milliseconds const twoHours = ms('2h'); // 7200000 const tenMinutes = ms('10 minutes'); // 600000 const halfDay = ms('0.5d'); // 43200000 const oneWeek = ms('1 week'); // 604800000 const twoMonths = ms('2 months'); // 5259600000 const oneYear = ms('1y'); // 31557600000 // Negative values are supported const negativeTime = ms('-3 days'); // -259200000 // Numeric strings return as-is const rawMs = ms('500'); // 500 // Format milliseconds to short strings const shortFormat = ms(60000); // "1m" const hours = ms(3600000); // "1h" const days = ms(172800000); // "2d" // Format with long option for human-readable output const longMinute = ms(60000, { long: true }); // "1 minute" const longHours = ms(7200000, { long: true }); // "2 hours" const longDays = ms(259200000, { long: true }); // "3 days" // Practical example: timeout configuration const cacheTimeout = ms('24 hours'); // 86400000 const sessionExpiry = ms('30 days'); // 2592000000 // Practical example: displaying elapsed time const startTime = Date.now(); // ... some operations ... const elapsed = Date.now() - startTime; console.log(`Operation took ${ms(elapsed, { long: true })}`); // Output: "Operation took 2 seconds" ``` -------------------------------- ### Strict Type Checking with ms.parseStrict Source: https://github.com/vercel/ms/blob/main/README.md Demonstrates how to use `parseStrict` for enhanced type safety when converting strings to milliseconds. This function throws a TypeScript error if the input string is not a valid format, ensuring stricter validation. ```typescript import { parseStrict } from 'ms'; parseStrict('1h'); // 3600000 function example(s: string) { return parseStrict(str); // tsc error } ``` -------------------------------- ### Convert time strings to milliseconds (ms) Source: https://github.com/vercel/ms/blob/main/README.md Converts various string representations of time into their equivalent millisecond values. Supports units like days, hours, minutes, seconds, and years. Fractional values and negative durations are also handled. If no unit is provided, it defaults to milliseconds. ```typescript import ms from 'ms'; ms('2 days'); // 172800000 ms('1d'); // 86400000 ms('10h'); // 36000000 ms('2.5 hrs'); // 9000000 ms('2h'); // 7200000 ms('1m'); // 60000 ms('5s'); // 5000 ms('1y'); // 31557600000 ms('100'); // 100 ms('-3 days'); // -259200000 ms('-1h'); // -3600000 ms('-200'); // -200 ``` -------------------------------- ### Milliseconds to String Formatting with format (JavaScript) Source: https://context7.com/vercel/ms/llms.txt The `format` function converts a number of milliseconds into a human-readable string. It supports both a default short format and an optional long format with full unit names and pluralization. This function is useful for displaying durations like uptime or countdowns. ```javascript import { format } from 'ms'; // Short format (default) const shortMs = format(500); // "500ms" const shortSec = format(1000); // "1s" const shortMin = format(60000); // "1m" const shortHour = format(3600000); // "1h" const shortDay = format(86400000); // "1d" const shortWeek = format(604800000); // "1w" const shortMonth = format(2629800000); // "1mo" const shortYear = format(31557600000); // "1y" // Long format with { long: true } const longMs = format(500, { long: true }); // "500 ms" const longSec = format(1000, { long: true }); // "1 second" const longMultiSec = format(5000, { long: true }); // "5 seconds" const longMin = format(60000, { long: true }); // "1 minute" const longMultiMin = format(300000, { long: true }); // "5 minutes" const longHour = format(3600000, { long: true }); // "1 hour" const longMultiHour = format(36000000, { long: true }); // "10 hours" const longDay = format(86400000, { long: true }); // "1 day" const longMultiDay = format(518400000, { long: true }); // "6 days" // Negative values const negativeShort = format(-60000); // "-1m" const negativeLong = format(-3600000, { long: true }); // "-1 hour" // Automatic rounding to largest unit const mixedTime = format(234234234); // "3d" const mixedLong = format(234234234, { long: true }); // "3 days" // Practical example: uptime display function displayUptime(startTime: number): string { const uptime = Date.now() - startTime; return `Server uptime: ${format(uptime, { long: true })}`; } // Practical example: countdown timer function formatCountdown(milliseconds: number): string { if (milliseconds <= 0) return 'Expired'; return `Expires in ${format(milliseconds, { long: true })}`; } const expiresIn = formatCountdown(7200000); // "Expires in 2 hours" ``` -------------------------------- ### TypeScript custom Template Literal Type for ms Source: https://github.com/vercel/ms/blob/main/README.md Shows how to create a custom Template Literal Type in TypeScript to further narrow down the accepted string formats for the `ms` function. This allows for more specific type checking based on expected units like 'days' or 'weeks'. ```typescript import { ms } from 'ms'; type OnlyDaysAndWeeks = `${number} ${'days' | 'weeks'}`; function example(value: OnlyDaysAndWeeks) { ms(value); } example('5.2 days'); // Valid // example('10 hours'); // This would cause a TypeScript error ``` -------------------------------- ### ms: Parse Time Strings to Milliseconds Source: https://context7.com/vercel/ms/llms.txt The `parse` function specifically converts a time string into its millisecond representation. It handles various units, including long-form and abbreviated versions, as well as decimal values. Invalid inputs will result in `NaN`. ```typescript import { parse } from 'ms'; // Basic unit conversions const seconds = parse('5s'); // 5000 const minutes = parse('10m'); // 600000 const hours = parse('2h'); // 7200000 const days = parse('3d'); // 259200000 const weeks = parse('2w'); // 1209600000 const months = parse('1mo'); // 2629800000 const years = parse('1y'); // 31557600000 // Long-form units (case-insensitive) const longSeconds = parse('30 seconds'); // 30000 const longMinutes = parse('5 minutes'); // 300000 const longHours = parse('2 hours'); // 7200000 const longDays = parse('7 days'); // 604800000 // Abbreviated variations const secsAbbrev = parse('10 secs'); // 10000 const minsAbbrev = parse('5 mins'); // 300000 const hrsAbbrev = parse('2 hrs'); // 7200000 const msecAbbrev = parse('100 msecs'); // 100 // Decimal values const halfHour = parse('0.5h'); // 1800000 const quarterDay = parse('.25d'); // 21600000 const negativeDecimal = parse('-1.5h'); // -5400000 // Invalid inputs return NaN const invalid = parse('invalid'); // NaN const notParseable = Number.isNaN(parse('foo')); // true // Practical example: configuration parsing function parseTimeout(config: string): number { const timeout = parse(config); if (Number.isNaN(timeout)) { throw new Error(`Invalid timeout value: ${config}`); } return timeout; } const serverTimeout = parseTimeout('30 seconds'); // 30000 const dbTimeout = parseTimeout('5m'); // 300000 ``` -------------------------------- ### Type-Safe String Parsing with parseStrict (TypeScript) Source: https://context7.com/vercel/ms/llms.txt The `parseStrict` function enables type-safe parsing of time strings into milliseconds. It enforces valid `StringValue` types at compile time, preventing runtime errors. This function is useful for defining typed configurations and function parameters related to time durations. ```typescript import { parseStrict, type StringValue } from 'ms'; // Type-safe parsing - these compile successfully const hours = parseStrict('2h'); // 7200000 const minutes = parseStrict('30 minutes'); // 1800000 const days = parseStrict('7d'); // 604800000 const mixed = parseStrict('1.5 hours'); // 5400000 // Using the StringValue type for function parameters function setExpirationTime(duration: StringValue): number { return parseStrict(duration); } // These are type-safe calls const tokenExpiry = setExpirationTime('1h'); // 3600000 const sessionExpiry = setExpirationTime('24h'); // 86400000 const cacheExpiry = setExpirationTime('5 minutes'); // 300000 // Custom type for restricted time inputs type CacheDuration = `${number} ${'hours' | 'days'}`; function setCacheDuration(duration: CacheDuration): number { return parseStrict(duration); } const shortCache = setCacheDuration('6 hours'); // 21600000 const longCache = setCacheDuration('30 days'); // 2592000000 // Practical example: typed configuration object interface AppConfig { sessionTimeout: StringValue; cacheExpiry: StringValue; tokenLifetime: StringValue; } function initializeApp(config: AppConfig) { return { sessionMs: parseStrict(config.sessionTimeout), cacheMs: parseStrict(config.cacheExpiry), tokenMs: parseStrict(config.tokenLifetime), }; } const appSettings = initializeApp({ sessionTimeout: '30 minutes', cacheExpiry: '1 hour', tokenLifetime: '7 days', }); // Result: { sessionMs: 1800000, cacheMs: 3600000, tokenMs: 604800000 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.