Recommended 22 practical one line Javascript code Date Daquan, recommended collection

In daily development, Date is often used by us. Some commonly used UI frameworks, such as Antd and ElementUI, use things like moment js,day.js time tool library to deal with their components about time, but when we break away from these frameworks and want to solve a problem about time conversion, it is redundant to introduce a time tool library. Therefore, here we share 22 practical one-line Javascript and typescript codes about Date. It is recommended to collect and read!

Pre knowledge

Intl object is a namespace of ECMAScript internationalization API, which provides precise string comparison, number formatting, and date time formatting. Constructors for Collator, NumberFormat, and DateTimeFormat objects are properties of Intl objects. understand more

Intl.DateTimeFormat is a constructor that formats date and time objects according to the language

Syntax:

// locales is the language
new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])
// Format the date of the corresponding language. Date is the date instance and returns the date string
new Intl.DateTimeFormat(locale).format(date)
// Get time zone
Intl.DateTimeFormat().resolvedOptions().timeZone

22 practical one line Javascript and typescript codes for Date

Add AM/PM for hours

JavaScript version

// `h ` is the number of hours between 0 and 23
const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;

TypeScript version

const suffixAmPm = (h: number): string => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;

Demo

suffixAmPm(0); // '12am'
suffixAmPm(5); // '5am'
suffixAmPm(12); // '12pm'
suffixAmPm(15); // '3pm'
suffixAmPm(23); // '11pm'

Calculate the number of days of difference between two dates

JavaScript version

const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));

TypeScript version

const diffDays = (date: Date, otherDate: Date): number => Math.ceil(Math.abs(date.valueOf() - otherDate.valueOf()) / (1000 * 60 * 60 * 24));

Demo

diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839

Calculate the number of months between two dates

JavaScript version

const monthDiff = (startDate, endDate) => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());

TypeScript version

const monthDiff = (startDate: Date, endDate: Date): number => Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());

Demo

monthDiff(new Date('2020-01-01'), new Date('2021-01-01')); // 12

Compare two dates

JavaScript version

// `a 'and' b 'are instances of' Date '
const compare = (a, b) => a.getTime() > b.getTime();

TypeScript version

const compare = (a: Date, b: Date): boolean => a.getTime() > b.getTime();

Demo

compare(new Date('2020-03-30'), new Date('2020-01-01')); // true

Convert date to YYYY-MM-DD format

JavaScript version

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

TypeScript version

const formatYmd = (date: Date): string => date.toISOString().slice(0, 10);

Demo

formatYmd(new Date()); // 2020-05-06

Convert seconds to hh:mm:ss format

JavaScript version

// `s ` seconds
const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8);

// Or
const formatSeconds = (s) => new Date(s * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];

// Or
const formatSeconds = (s) => [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(':').replace(/\b(\d)\b/g, '0$1');

TypeScript version

const formatSeconds = (s: number): string => new Date(s * 1000).toISOString().substr(11, 8);

// Or
const formatSeconds = (s: number): string => (new Date(s * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/) as string[])[0];

// Or
const formatSeconds = (s: number): string => (
    [parseInt(`${s / 3600}`), parseInt(`${(s / 60) % 60}`), parseInt(`${s % 60}`)].join(':').replace(/\b(\d)\b/g, '0$1')
);

Demo

formatSeconds(200); // 00:03:20
formatSeconds(500); // 00:08:20

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

JavaScript version

// `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]

TypeScript version

const extract = (date: Date): string[] =>
    date
        .toISOString()
        .split(/[^0-9]/)
        .slice(0, -1);

Demo

extract(new Date()); // ['2021', '12', '09', '04', '48', '36', '600']

Formats the date for the given locale

JavaScript version

// `Date ` is a 'date' object 
// `Locale ` is a locale (e.g. en US, Pt BR)
const format = (date, locale) => new Intl.DateTimeFormat(locale).format(date);

TypeScript version

const format = (date: Date, locale: string): string => new Intl.DateTimeFormat(locale).format(date);

Demo

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

Gets the current quarter of the date

JavaScript version

const getQuarter = (d = new Date()) => Math.ceil((d.getMonth() + 1) / 3);

TypeScript version

const getQuarter = (d = new Date()): number => Math.ceil((d.getMonth() + 1) / 3);

Gets the current timestamp in seconds

JavaScript version

const ts = () => Math.floor(new Date().getTime() / 1000);

TypeScript version

const ts = (): number => Math.floor(new Date().getTime() / 1000);

Gets the day of the year from the date

JavaScript version

// `Date ` is a 'date' object 
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));

TypeScript version

const dayOfYear = (date: Date): number => Math.floor((date.valueOf() - new Date(date.getFullYear(), 0, 0).valueOf()) / (1000 * 60 * 60 * 24));

Demo

dayOfYear(new Date(2020, 04, 16)); // 137

Gets the first date of the month in which the date is located

JavaScript version

const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1);

TypeScript version

const getFirstDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth(), 1);

Gets the last date of the month in which the date is located

JavaScript version

const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 1, 0);

TypeScript version

const getLastDate = (d = new Date()): Date => new Date(d.getFullYear(), d.getMonth() + 1, 0);

Gets the month name of the date

JavaScript version

// `Date ` is a date object
const getMonthName = (date) => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', ' November', 'December'][date.getMonth()];

TypeScript version

const getMonthName = (date: Date): string => ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', ' November', 'December'][date.getMonth()];

Gets the number of days in a given month

JavaScript version

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

TypeScript version

const daysInMonth = (month: number, year: number): number => new Date(year, month, 0).getDate();

Get time zone string

JavaScript version

const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;

TypeScript version

const getTimezone = (): string => Intl.DateTimeFormat().resolvedOptions().timeZone;

Demo

getTimezone(); // 'Asia/Saigon'

Get tomorrow's date

JavaScript version

const tomorrow = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());

// Or
const tomorrow = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24);

TypeScript version

const tomorrow: Date = ((d) => new Date(d.setDate(d.getDate() + 1)))(new Date());

// Or
const tomorrow: Date = new Date(new Date().valueOf() + 1000 * 60 * 60 * 24);

Gets the total number of days in a year

JavaScript version

const numberOfDays = (year) => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);

// Or
const numberOfDays = (year) => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);

TypeScript version

const numberOfDays = (year: number): number => ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 366 : 365);

// Or
const numberOfDays = (year: number): number => (new Date(year, 1, 29).getDate() === 29 ? 366 : 365);

Gets the working day of the date

JavaScript version

// `date` is a Date object
const getWeekday = (date) => ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];

TypeScript version

const getWeekday = (date: Date): string => ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];

Get yesterday's date

JavaScript version

const yesterday = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());

// Or
const yesterday = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);

TypeScript version

const yesterday: Date = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());

// Or
const yesterday: Date = new Date(new Date().valueOf() - 1000 * 60 * 60 * 24);

Initializes the current date but sets the time to midnight

JavaScript version

const midnightOfToday = () => new Date(new Date().setHours(0, 0, 0, 0));

TypeScript version

const midnightOfToday = (): Date => new Date(new Date().setHours(0, 0, 0, 0));

Sort date array

JavaScript version

// `arr ` is an array containing ` Date 'items
const sortDescending = (arr) => arr.sort((a, b) => a.getTime() > b.getTime());

const sortAscending = (arr) => arr.sort((a, b) => a.getTime() < b.getTime());

TypeScript version

const sortDescending = (arr: Date[]): Date[] => arr.sort((a, b) => a.getTime() - b.getTime());

const sortAscending = (arr: Date[]): Date[] => arr.sort((a, b) => b.getTime() - a.getTime());

Keywords: Javascript

Added by Rohan Shenoy on Sat, 25 Dec 2021 06:56:13 +0200