Javascript datetime tips

calculate-the-number-of-difference-days-between-two-dates

const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
// diffDays(new Date('2014-12-19'), new Date('2020-01-01')) === 1839

Check if a date is today

// `date` is a Date object
const isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10);

Convert a date to yyyy mm dd format

// `date` is a `Date` object
const formatYmd = date => date.toISOString().slice(0, 10);

// formatYmd(new Date()) returns `2020-05-06`

Extract year month day hour minute second and millisecond from a date

// `date` is a `Date` object
const extract = date => date.toISOString().split(/[^0-9]/).slice(0, -1);

// `extract` is an array of [year, month, day, hour, minute, second, millisecond]

Format a date for the given locale

// `date` is a `Date` object
// `locale` is a locale (en-US, pt-BR, for example)
const format = (date, locale) => new Intl.DateTimeFormat(locale).format(date);

// format(new Date(), 'pt-BR') returns `06/05/2020`

Get the number of days in given month

// `month` is zero-based index
const daysInMonth = (month, year) => new Date(year, month, 0).getDate();