Skip to main content

Using Time Utilities


Often working with Date related objects can be hard to handle. @sapphire/time-utilities is a small package that contains a few utility classes that eases working with these kind of objects.


npm install @sapphire/time-utilities


Time utilities comes with a few enums that can be used to represent time units and to simplify the extra unit conversions. For example


import { Time } from '@sapphire/time-utilities';console.log(Time.Day * 1); // 86400000

Similarly other enum members represent time intervals too. Please see more enum members in the documentation.


Since this package contains multiple utility classes, we will cover each one by one.


Cron class can be used to process the cron strings. It can be used to get the next time a cron job should be executed. By default it uses the current UTC time to compare. However, you can pass a Time object to compare with too in next method.

import { Cron } from '@sapphire/time-utilities';const cronTime = new Cron('0 * * * *');console.log(;// logs next hour timeconsole.log( Date('2022-04-24T19:30:00Z')));// 2022-04-24T20:00:00.000Z


Duration class can be used to convert a human readable time string to milliseconds.

import { Duration } from '@sapphire/time-utilities';const duration = new Duration('1d');console.log(duration);// { offset: 86400000 }console.log(duration.fromNow);// Logs the date from now


DurationFormatter class can be used to convert milliseconds duration to a human readable string.

import { DurationFormatter } from '@sapphire/time-utilities';const ms = new DurationFormatter().format(3600000);console.log(ms);// 1 hour


TimerManager class can be used to manage timers. It can be used to create a timer that will be executed every X milliseconds as well as to set a timeout.

import { TimerManager } from '@sapphire/time-utilities';function guideTimerManager(message: string) {  console.log(message);}TimerManager.setTimeout(() => {  guideTimerManager('After 2 seconds');}, 2000);TimerManager.setInterval(() => {  guideTimerManager('I run per minute');}, 60000);


Timestamp class contains multiple methods that can be used to deal with timestamps easily. Let's see a quick example of how to use it.


import { Timestamp } from '@sapphire/time-utilities';const timestamp = new Timestamp('HH:mm:ss');console.log(timestamp.display(3600000));// 06:30:00// edit the initialized pattern to include date, month and year in timestamptimestamp.edit('DD-MM-YYYY HH:mm:ss');console.log(timestamp.display(3600000));// 01-01-1970 06:30:00// convert a date to UTC dateconsole.log(Timestamp.utc('2022-04-25'));// 2022-04-24T18:30:00.000Z