Skip to content

Datetime

Metro UI provides a set of methods and properties for working with Dates and Time.

The Datetime class provides a set of methods and properties for working with dates and time.

Metro UI already includes the Datetime library. You can use it without any additional installation, but if you want to use it in your project, you can install it with package manager:

Terminal window
npm install @olton/datetime

or use CDN:

<script type="module">
import { Datetime, datetime } from "https://esm.run/@olton/datetime";
</script>

To create a new instance of Datetime, you can use the Datetime class or the factory function datetime.

const dt = new Datetime();
const dt2 = datetime();
console.log(dt.calendar());

The Datetime class provides a set of methods and properties for working with dates and time.

const dt = new Datetime();

When you create a class DateTime you can specify the original date value in the same format as when using JavaScript object Date.

Beginning options:

OptionTypeDefaultDescription
localeStringenThe datetime locale.
utcModeBooleanfalseUTC mode.
weekStartNumber0From locale.
mutableBooleantrueIs mutable state.

You can change options after creating an instance of Datetime:

const dt = new Datetime();
dt.useLocale('ua');
dt.immutable(true)

This property contains the list of available locales.

This method checks if the value is a Datetime instance.

const dt = new Datetime();
Datetime.isDatetime(dt); // true

This method returns the current date and time as a Datetime instance as date or as timestamp.

const asDate = true
Datetime.now(); // timestamp
Datetime.now(asDate); // date

This method parses a date string and returns a Datetime instance.

const dt = Datetime.parse('2023-10-01 12:00:00');
console.log(dt.format('YYYY-MM-DD HH:mm:ss')); // 2023-10-01 12:00:00

This method creates a Datetime instance from a date string from(str, locale, format).

You can use the format parts:

const parts = {
"month": ["M", "mm", "%m"],
"day": ["D", "dd", "%d"],
"year": ["YY", "YYYY", "yy", "yyyy", "%y"],
"hour": ["h", "hh", "%h"],
"minute": ["m", "mi", "i", "ii", "%i"],
"second": ["s", "ss", "%s"],
"ms": ["sss"]
}
const dt = Datetime.from('Dec, 2025, 01', 'en', 'm, yyyy, dd');

Add locale to the list of available locales.

Datetime.setLocale('en', {
months: "January February March April May June July August September October November December".split(" "),
monthsShort: "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),
weekdays: "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),
weekdaysShort: "Sun Mon Tue Wed Thu Fri Sat".split(" "),
weekdaysMin: "Su Mo Tu We Th Fr Sa".split(" "),
weekStart: 0
});

This method returns the required locale.

Datetime.getLocale('en');

This method aligns the date to the start of the required datetime part.

Datetime.align('2023-01-10 12:00:00', 'month'); // 2023-01-01 00:00:00
Datetime.align('2023-10-01 12:00:00', 'day'); // 2023-10-01 00:00:00

You can align to the following parts:

PartDescription
yearAlign to the start of the year.
monthAlign to the start of the month.
weekAlign to the start of the week.
dayAlign to the start of the day.
hourAlign to the start of the hour.
minuteAlign to the start of the minute.
secondAlign to the start of the second.
quarterAlign to the start of the second.

This method aligns the date to the end of the required datetime part.

Datetime.alignEnd('2023-01-10 12:00:00', 'month'); // 2023-01-31 23:59:59
Datetime.alignEnd('2023-10-01 12:00:00', 'day'); // 2023-10-01 23:59:59

This method parses a time string and returns a Datetime instance.

const dt = Datetime.parseTime('255d, 12h, 00m, 00s');

This method sorts an array of Datetime instances.

const dt1 = new Datetime(...);
const dt1 = new Datetime(...);
const dt1 = new Datetime(...);
const sorted = Datetime.sort([dt1, dt2, dt3]);

This method checks if the Datetime instance is tomorrow.

Datetime.isTomorrow('2023-10-02 12:00:00');

This method checks if the Datetime instance is yesterday.

Datetime.isYesterday('2023-09-30 12:00:00');

This method sets the mutable option to the instance of Datetime.

const dt = new Datetime();
dt.immutable(true); // immutable
dt.immutable(false); // mutable

This method sets the utcMode for instance to true.

const dt = new Datetime();
dt.utc(); // now utc

This method sets the utcMode for instance to false.

const dt = new Datetime();
dt.local(); // now local

This method sets the locale for instance.

const dt = new Datetime();
dt.useLocale('en'); // now en

This method returns a clone of the Datetime instance.

const dt = new Datetime();
const dt2 = dt.clone(); // clone

This method aligns the date to the start of the required datetime part.

const dt = new Datetime();
dt.align('month'); // align to month

This method aligns the date to the end of the required datetime part.

const dt = new Datetime();
dt.alignEnd('month'); // align to month

This method returns the value of the Datetime instance if argument is undefined, and sets new value if you specify the argument method.

const dt = new Datetime();
dt.val('2023-10-01 12:00:00'); // set value
console.log(dt.val()); // get value

This method returns the last two numbers of year of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.year2(); // 23

Sets or gets the milliseconds of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.ms(); // 0
dt.ms(1000); // set milliseconds
console.log(dt.ms()); // 1000

Sets or gets the seconds of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.second(); // 0
dt.second(30); // set seconds
console.log(dt.second()); // 30

Sets or gets the minutes of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.minute(); // 0
dt.minute(30); // set minutes
console.log(dt.minute()); // 30

Sets or gets the hours of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.hour(); // 12
dt.hour(18); // set hours
console.log(dt.hour()); // 18

Sets or gets the day of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.day(); // 1
dt.day(15); // set day
console.log(dt.day()); // 15

Sets or gets the month of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.month(); // 10
dt.month(5); // set month
console.log(dt.month()); // 5

Sets or gets the year of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.year(); // 2023
dt.year(2025); // set year
console.log(dt.year()); // 2025

Sets or gets the time of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.time(); // 12:00:00
dt.time('18:30:00'); // set time
console.log(dt.time()); // 18:30:00

Sets or gets the week day of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.weekDay(); // 0
dt.weekDay(5); // set week day
console.log(dt.weekDay()); // 5

This method returns the value of the specified part of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.get('year'); // 2023
dt.get('month'); // 10

This method sets the value of the specified part of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.set('year', 2025); // set year

This method adds the specified value to the specified part of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.add(2, 'day'); // add 2 days
dt.add(-2, 'day'); // sub 2 days

This method adds the specified value to the hour of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.addHour(2); // add 2 hours
dt.addHour(-2); // sub 2 hours

This method adds the specified value to the minute of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.addMinute(2); // add 2 minutes

This method adds the specified value to the second of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.addSecond(2); // add 2 seconds

This method adds the specified value to the milliseconds of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.addMs(2); // add 2 milliseconds

This method adds the specified value to the week of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.addWeek(2); // add 2 weeks

This method adds the specified value to the month of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.addMonth(2); // add 2 months

This method adds the specified value to the year of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.addYear(2); // add 2 years

This method formats the Datetime instance to the specified format.

const dt = new Datetime("2023-10-01 12:00:00");
dt.format('YYYY-MM-DD'); // 2023-10-01
dt.format('YYYY-MM-DD HH:mm:ss'); // 2023-10-01 12:00:00
dt.format('YYYY-MM-DD HH:mm:ss.SSS'); // 2023-10-01 12:00:00.000
FormatDescription
YYYear with century (25)
YYYYYear with century (2025)
MMonth (1-12)
MMMonth (01-12)
MMMMon short name (3 symbols)
MMMMMonth full name
DDay (1-31)
DDDay (01-31)
dWeek day
ddWeek day (2 symb)
ddddWeek day full
hHours (0-11)
hhHours (00-11)
HHours (0-23)
HHHours (00-23)
mMinutes (0-59)
mmMinutes (00-59)
sSeconds (0-59)
ssSeconds (00-59)
sssMilliseconds
BBbuddhist
BBBBbuddhist
CCentury
aam/pm
AAM/PM
IISO week day
zTimezone name
ZTimezone
ZZTimezone
ZZZTimezone
WWeek number
WWWeek number
WWWWeek number
WWWWWeek number

This method returns the value of the Datetime instance as a timestamp.

const dt = new Datetime("2023-10-01 12:00:00");
dt.valueOf(); // 1696156800000

This method returns the value of the Datetime instance as a string.

const dt = new Datetime("2023-10-01 12:00:00");
dt.toString(); // 2023-10-01 12:00:00

Return the Buddhist date.

const dt = new Datetime("2023-10-01 12:00:00");
dt.buddhist(); // 2566-10-01 12:00:00

Generate calendar for the month of the Datetime instance for the given date. You can specify the weekStart option to set the first day of the week.

const dt = new Datetime("2023-10-01 12:00:00");
const calendar = dt.calendar();
console.log(calendar);

The calendar includes the following properties:

const result = {
month: String,
days: Number[],
weekstart: 1 | 0,
weekdays: [],
today: now.format("YYYY-MM-DD"),
weekends: [],
week: []
}

This method returns the century of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.century(); // 21

You can compare two Datetime instances using the following methods:

This method checks if two Datetime instances are the same.

const dt1 = new Datetime("2023-10-01 12:00:00");
const dt2 = new Datetime("2023-10-01 12:00:00");
const dt3 = new Datetime("2023-10-01 12:00:01");
console.log(dt1.same(dt2)); // true
console.log(dt1.same(dt3)); // false

This method compares two Datetime instances with aligned dates specified and operator (=, !=, <, >, <=, >=).

const dt1 = new Datetime("2023-10-01 12:00:00");
const dt2 = new Datetime("2023-10-01 12:00:00");
const dt3 = new Datetime("2023-10-01 12:00:01");
console.log(dt1.compare(dt2, '=')); // true
console.log(dt1.compare(dt3, '<')); // true
console.log(dt1.compare(dt3, '>')); // false
console.log(dt1.compare(dt3, '<=')); // true
console.log(dt1.compare(dt3, '>=')); // false
console.log(dt1.compare(dt3, '!=')); // true

This method checks if the Datetime instance is between two other Datetime instances.

const dt1 = new Datetime(...);
const dt2 = new Datetime(...);
const dt3 = new Datetime(...);
d3.between(dt1, dt2);

This method checks if the Datetime instance is older than the specified Datetime instance.

const dt1 = new Datetime(...);
const dt2 = new Datetime(...);
dt1.older(dt2);

This method checks if the Datetime instance is older or equal to the specified Datetime instance.

const dt1 = new Datetime(...);
const dt2 = new Datetime(...);
dt1.olderOrEqual(dt2);

This method checks if the Datetime instance is younger than the specified Datetime instance.

const dt1 = new Datetime(...);
const dt2 = new Datetime(...);
dt1.younger(dt2);

This method checks if the Datetime instance is younger or equal to the specified Datetime instance.

const dt1 = new Datetime(...);
const dt2 = new Datetime(...);
dt1.youngerOrEqual(dt2);

This method checks if the Datetime instance is equal to the specified Datetime instance.

const dt1 = new Datetime(...);
const dt2 = new Datetime(...);
dt1.equal(dt2);

This method checks if the Datetime instance is not equal to the specified Datetime instance.

const dt1 = new Datetime(...);
const dt2 = new Datetime(...);
dt1.notEqual(dt2);

This method returns the difference between two Datetime instances in the specified unit.

const dt1 = new Datetime(...);
const dt2 = new Datetime(...);
dt1.diff(dt2, 'day');

You can specify the following units: ms, second, minute, hour, day, month, year.

This method returns the distance between two Datetime instances in the specified unit and aligned dates.

const dt1 = new Datetime(...);
const dt2 = new Datetime(...);
dt1.distance(dt2, 'day');

This method returns the day of the year of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.dayOfYear(); // 274

This method returns the number of days in the month of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.daysInMonth(); // 31

This method returns the number of days in the year of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.daysInYear(); // 365

This method returns the number of days in the year of the Datetime instance as array, where values - days count in month.

const dt = new Datetime("2023-10-01 12:00:00");
dt.daysInYearMap(); // [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

This method returns the number of days in the year of the Datetime instance as object, where keys - month names, values - days count in month.

const locale = 'en';
const useShortName = true;
const dt = new Datetime("2023-10-01 12:00:00");
dt.daysInYearObj(locale, useShortName); // {Jan: 31, Feb: 28, Mar: 31, Apr: 30, May: 31, Jun: 30, Jul: 31, Aug: 31, Sep: 30, Oct: 31, Nov: 30, Dec: 31}

This method returns the decade of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.decade(); // 2020

This method returns the start of the decade of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.decadeStart(); // 2020-01-01 00:00:00

This method returns the end of the decade of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.decadeEnd(); // 2029-12-31 23:59:59

This method returns the decade of the month of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.decadeOfMonth(); // 0

This method returns the AM/PM of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.ampm(); // PM

This method returns the hour of the Datetime instance in 12 hours format.

const dt = new Datetime("2023-10-01 12:00:00");
dt.hour12(); // 12

This method checks if the Datetime instance is a leap year.

const dt = new Datetime("2023-10-01 12:00:00");
dt.isLeapYear(); // false

This method returns the iso week day of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.isoWeekDay();

This method returns the maximum date of the Datetime instance.

const dt1 = new Datetime(...);
const dt4 = new Datetime(...);
const dt3 = new Datetime(...);
const dt2 = new Datetime(...);
const dt5 = new Datetime(...);
dt1.max(dt2, dt3, dt4, dt5);
Datetime.max(dt1, dt2, dt3, dt4, dt5);

This method returns the minimum date of the Datetime instance.

const dt1 = new Datetime(...);
const dt4 = new Datetime(...);
const dt3 = new Datetime(...);
const dt2 = new Datetime(...);
const dt5 = new Datetime(...);
dt1.min(dt2, dt3, dt4, dt5);
Datetime.min(dt1, dt2, dt3, dt4, dt5);

This method returns the moon phase of the Datetime instance.

const phases = [
'new-moon',
'waxing-crescent',
'first-quarter',
'waxing-gibbous',
'full-moon',
'waning-gibbous',
'last-quarter',
'waning-crescent'
]
const dt = new Datetime("2023-10-01 12:00:00");
dt.moon();

This method returns the quarter of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.quarter(); // 4

This method adds the specified value to the quarter of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.addQuarter(2); // add 2 quarters
dt.add(2, "quarter"); // add 2 quarters

This method formats the Datetime instance to the specified format using the strftime format.

const dt = new Datetime("2023-10-01 12:00:00");
dt.strftime('%Y-%m-%d %H:%M:%S'); // 2023-10-01 12:00:00

You can use the following format parts:

const matches = {
'%a': names.weekdaysShort[weekDay],
'%A': names.weekdays[weekDay],
'%b': names.monthsShort[month],
'%h': names.monthsShort[month],
'%B': names.months[month],
'%c': this.toString().substring(0, this.toString().indexOf(" (")),
'%C': this.century(),
'%d': aDay,
'%D': [aDay, aMonth, year].join("/"),
'%e': day,
'%F': [year, aMonth, aDay].join("-"),
'%G': thursday().year(),
'%g': (""+thursday().year()).slice(2),
'%H': aHour,
'%I': aHour12,
'%j': lpad(this.dayOfYear(), 0, 3),
'%k': aHour,
'%l': aHour12,
'%m': aMonth,
'%n': month + 1,
'%M': aMinute,
'%p': this.ampm(),
'%P': this.ampm(true),
'%s': Math.round(time / 1000),
'%S': aSecond,
'%u': this.isoWeekDay(),
'%V': this.isoWeekNumber(),
'%w': weekDay,
'%x': this.toLocaleDateString(),
'%X': this.toLocaleTimeString(),
'%y': year2,
'%Y': year,
'%z': this.timezone().replace(":", ""),
'%Z': this.timezoneName(),
'%r': [aHour12, aMinute, aSecond].join(":") + " " + this.ampm(),
'%R': [aHour, aMinute].join(":"),
"%T": [aHour, aMinute, aSecond].join(":"),
"%Q": aMs,
"%q": ms,
"%t": this.timezone()
};

This method returns the time lapse from beginning time.

const dt = new Datetime("2023-10-01 12:00:00");
// sleep for 2 seconds
dt.timelapse(); // few sec

This method returns the UTC offset of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.utcOffset();

This method returns the timezone of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.timezone(); // +0300

This method returns the timezone name of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.timezoneName(); // Europe/Kiev

This method checks if the Datetime instance is today.

const dt = new Datetime("2023-10-01 12:00:00");
dt.isToday(); // true

This method returns the current date as a Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.today(); // 2023-10-01 12:00:00

This method returns the tomorrow date as a Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.tomorrow(); // 2023-10-02 12:00:00

This method checks if the Datetime instance is tomorrow.

const dt = new Datetime("2023-10-01 12:00:00");
dt.isTomorrow(); // false
  • toDateString()
  • toISOString()
  • toJSON()
  • toGMTString()
  • toLocaleDateString
  • toLocaleString()
  • toLocaleTimeString()
  • toTimeString()
  • toUTCString()
  • toDate()

Sets or gets unix timestamp of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.unix();
dt.unix(1696156800);

This method returns the unix timestamp of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.timestamp();

This method returns the week number of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.weekNumber(); // 40

This method returns the ISO week number of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.isoWeekNumber(); // 40

This method returns the number of weeks in the year of the Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.weeksInYear(); // 52

This method returns the yesterday date as a Datetime instance.

const dt = new Datetime("2023-10-01 12:00:00");
dt.yesterday(); // 2023-09-30 12:00:00

This method checks if the Datetime instance is yesterday.

const dt = new Datetime("2023-10-01 12:00:00");
dt.isYesterday(); // false