to-duration
v1.0.0
Published
A powerful collection of functions to convert a duration object into a number in any time unit
Downloads
72
Maintainers
Readme
to-duration
A powerful collection of functions to convert a duration object into a number in any time unit.
Use toMilliseconds({ days: 3 }) instead of 3 * 24 * 60 * 60 * 1_000.
TypeScript-first, works with both ESM and CommonJS.
Installation
npm install to-durationExamples
Recurring tasks
import { toMilliseconds } from 'to-duration';
setInterval(syncMetrics, toMilliseconds({ minutes: 5 }));Long-running requests
import { toMilliseconds } from 'to-duration';
const response = await fetch('/api/heavy-report', {
signal: AbortSignal.timeout(toMilliseconds({ seconds: 30 })),
});S3 signed URLs
import { toSeconds } from 'to-duration';
import { GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const command = new GetObjectCommand({
Bucket: 'avatars',
Key: 'users/42.webp',
});
const url = await getSignedUrl(s3, command, {
expiresIn: toSeconds({ hours: 6 }),
});API
Conversion functions:
toYears({ days: 365 }) // 1 year
toMonths({ days: 90 }) // 3 months
toWeeks({ days: 42 }) // 6 weeks
toDays({ weeks: 1 }) // 7 days
toHours({ days: 1 }) // 24 hours
toMinutes({ hours: 2 }) // 120 minutes
toSeconds({ minutes: 5 }) // 300 seconds
toMilliseconds({ seconds: 5 }) // 5 000 milliseconds
toMicroseconds({ milliseconds: 9 }) // 9 000 microseconds
toNanoseconds({ microseconds: 1 }) // 1 000 nanosecondsDuration object
Functions accept an object with one or several units, at least one is required:
toSeconds({ days: 3, hours: 1, minutes: 1 }); // ✅ ok
toSeconds({}); // ❌ TypeScript errorDuration object type:
type Duration = {
years?: number;
months?: number;
weeks?: number;
days?: number;
hours?: number;
minutes?: number;
seconds?: number;
milliseconds?: number;
microseconds?: number;
nanoseconds?: number;
};How conversion works
Functions use fixed, simplified units for year and month:
| Unit | Equals | |-------------|--------------------| | year | 365 days | | month | 30 days | | week | 7 days | | day | 24 hours | | hour | 60 minutes | | minute | 60 seconds | | second | 1 000 milliseconds | | millisecond | 1 000 microseconds | | microsecond | 1 000 nanoseconds |
It does not account for leap years, DST, or real calendar month lengths. For calendar-aware calculations, use a proper date library.
Tests
Tests cover every conversion direction. See the test suite.
Related
Has a similar feel to Temporal.PlainDate.prototype.add({ days: 5 }), which also accepts a duration-like object.
If you only need to convert to milliseconds, check out the excellent @sindresorhus/to-milliseconds with similar interface.
License
MIT
