Skip to content

Instantly share code, notes, and snippets.

@AmyShackles
Last active March 4, 2021 21:48
Show Gist options
  • Save AmyShackles/e22343bfb4fd3ec539457e29b585c8c4 to your computer and use it in GitHub Desktop.
Save AmyShackles/e22343bfb4fd3ec539457e29b585c8c4 to your computer and use it in GitHub Desktop.
Reference for dealing with JS Date objects

const date = new Date('08-14-1989 13:21:45')

GETTERS

Get time (since Unix Epoch)

const birthday = new Date('1989-08-14');
birthday.getTime() // 619056000000

Get timezone offset (current locale/system settings vs. UTC)

const date = new Date(Date.now());
date.getTimezoneOffset(); // In my timezone, this returns 420.  Your mileage may vary.

Get seconds according to UTC

date.getUTCSeconds(); // 45

Get seconds

const seconds = date.getSeconds(); // 45

Get minutes according to UTC

const date = new Date('08-14-1989 13:21:45:22 GMT+3:30');
date.getUTCMinutes(); // 51

Get minutes

const minutes = date.getMinutes(); // 21

Get hours according to UTC

const date = new Date('08-14-1989 13:21:45 GMT-7:00');
date.getUTCHours(); // 20

Get hours

const hours = date.getHours(); // 13

Get milliseconds according to UTC

const date = new Date('08-14-1989 13:21:45:22 GMT-7:00');
date.getUTCMilliseconds(); // 22

Get milliseconds

const milliseconds = date.getMilliseconds(); // 0

Get day of the month according to UTC

const date = new Date('08-14-1989 17:21:45 GMT-8:00');
const utcDayOfMonth = date.getUTCDate(); // 15

Get day of month

const dayOfMonth = date.getDate(); // 14

Get day of week according to UTC

const date = new Date('08-14-1989 17:21:45 GMT-8:00');
const utcDayOfWeek = date.getUTCDay(); // 2

Get day of week

getDay() is 0-indexed starting with Sunday

const dayOfWeek = date.getDay(); // 1

Get month according to UTC

const date = new Date('December 31, 1989, 23:15:30 GMT-11:00');
date.getUTCMonth(); // 0

Get month

getMonth() is 0-indexed, so you might want to add 1 if you are using this for display purposes.

const month = date.getMonth() + 1; // 8

Get year according to UTC

const date = new Date('December 31, 1975, 23:15:30 GMT-11:00');
date.getUTCFullYear(); // 1976

Get year

getFullYear() is recommended over getYear()

const year = date.getFullYear() // 1989

SETTERS

Set hours according to UTC

// To create a new date object based on the modifications of another
const newUTCHours = new Date(new Date(date).setUTCHours(14)); // 1989-08-14T14:21:45.000Z

// To modify the date directly
date.setUTCHours(14); // 1989-08-14T14:21:45.000Z

Set hour

// To create a new date object based on the modification of another
const newHour = new Date(new Date(date).setHours(14)); //  1989-08-14T14:21:45.000Z

// To modify the date directly
date.setHours(14) // 1989-08-14T14:21:45.000Z,

Set minutes according to UTC

// To create a new date object based on the modification of another
const newUTCMinutes = new Date(new Date(date).setUTCMinutes(25)); // 1989-08-14T13:25:45.000Z 

// To modify the date directly
date.setUTCMinutes(25); // 1989-08-14T13:25:45.000Z 

Set minutes

// To create a new date object based on the modification of another
const newMinute = new Date(new Date(date).setMinutes(23)); // 1989-08-14T13:23:45.000Z

// To modify the date directly
date.setMinutes(23); // 1989-08-14T13:23:45.000Z

Set seconds according to UTC

// To create a new date object based on the modification of another
const newUTCSeconds = new Date(new Date(date).setUTCSeconds(33)); //  1989-08-14T13:21:33.000Z 
// To modify the date directly
date.setUTCSeconds(33); //  1989-08-14T13:21:33.000Z 

Set seconds

// To create a new date object based on the modification of another
const newSeconds = new Date(new Date(date).setSeconds(15)); //  1989-08-14T13:21:15.000Z

// To modify the date directly
date.setSeconds(15); // 1989-08-14T13:21:15.000Z

Set milliseconds according to UTC

// To create a new date object based on the modifcation of another
const newUTCMilliseconds = new Date(new Date(date).setUTCMilliseconds(70)); //  1989-08-14T13:21:45.070Z

// To modify the date directly
date.setUTCMilliseconds(70); //  1989-08-14T13:21:45.070Z

Set milliseconds

// To create a new date object based on the modification of another
const newMilliseconds = new Date(new Date(date).setMilliseconds(40)); // 1989-08-14T13:21:45.040Z

// To modify the date directly
date.setMilliseconds(40); // 1989-08-14T13:21:45.040Z

Set day of month according to UTC

// To create a new date object based on the modification of another
const newUTCDate = new Date(new Date(date).setUTCDate(19)); // 1989-08-19T13:21:45.000Z

// To modify the date directly
date.setUTCDate(19); // 1989-08-19T13:21:45.000Z

Set day of month

// To create a new date object based on the modifications of another
const newDayOfMonth = new Date(new Date(date).setDate(12)); // 1989-08-12T13:21:45.000Z

// To modify the date directly
date.setDate(12); // 1989-08-12T13:21:45.000Z

Set month according to UTC

// To create a new date object based on the modification of another
const newUTCMonth = new Date(new Date(date).setUTCMonth(3)); // 1989-04-14T13:21:45.000Z

// To modify the date directly
date.setUTCMonth(3); // 1989-04-14T13:21:45.000Z

Set month

// To create a new date object based on the modification of another
const newMonth = new Date(new Date(date).setMonth(7)); // 1989-08-14T13:21:45.000Z

// To modify the date directly
date.setMonth(7); // 1989-08-14T13:21:45.000Z

Set year according to UTC

const newYear = new Date(new Date(date).setUTCFullYear(1988)); // 1988-08-14T13:21:45.000Z

// To modify the date directly
date.setUTCFullYear(1988); // 1988-08-14T13:21:45.000Z

Set year

// To create a new date object based on the modification of another
const newYear = new Date(new Date(date).setFullYear(1988)); // 1988-08-14T13:21:45.000Z

// To modify the date directly
date.setFullYear(1988); // 1988-08-14T13:21:45.000Z

FORMATTING

Day of week, time

Desired output Mon, 1PM

We can get close with format(), but not all the way there.

const format1Close = new Intl.DateTimeFormat('en-US', {
    weekday: 'short', hour: 'numeric'}
    ).format(date); // 'Mon, 1 PM'

To get the rest of the way, we can use formatToParts()

const format1Success = new Intl.DateTimeFormat('en-US', {
    weekday: 'short', hour: 'numeric'
}).formatToParts(date).map(({type, value}) => {
    switch (type) {
        case 'literal':
            if (/^\s$/.test(value)) {
                return '';
            }
            return value;
        default: 
            return value;
    }
}).join('') // 'Mon, 1PM'

Desired output Monday, August 14 1989, 1:21:45 PM

We can use format() to get us most of the way there, but not all the way.

const format2Close = new Intl.DateTimeFormat('en-US', {
    weekday: 'long', 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric', 
    hour12:true, 
    hour: "numeric", 
    minute: "numeric", 
    second: "numeric"
}).format(date); // 'Monday, August 14, 1989, 1:21:45 PM'

We can use formatToParts() to get the exact format we want

const format2Success = new Intl.DateTimeFormat('en-US', {
        weekday: 'long', 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric', 
        hour12:true, 
        hour: "numeric", 
        minute: "numeric", 
        second: "numeric"
}).formatToParts(date).map(({type, value}, index) => {
    /* This is what the array currently being read looks like
    [
        {type: 'weekday': value 'Monday'},
        { type: 'literal', value: ', ' },
        { type: 'month', value: 'August' },
        { type: 'literal', value: ' ' },
        { type: 'day', value: '14' },
        { type: 'literal', value: ', ' }, // index 5
        { type: 'year', value: '1989' },
        { type: 'literal', value: ', ' },
        { type: 'hour', value: '1' },
        { type: 'literal', value: ':' },
        { type: 'minute', value: '21' },
        { type: 'literal', value: ':' },
        { type: 'second', value: '45' },
        { type: 'literal', value: ' ' },
        { type: 'dayPeriod', value: 'PM' }
    ]
    */
    if (index === 5) {
        return ' ';
    }
    return value;
}).join('') // 'Monday, August 14 1989, 1:21:45 PM'

Ranges

Desired output August 14, 1989 – January 16, 1991

const range = new Intl.DateTimeFormat('en', {
    month: 'long', day: 'numeric', year: 'numeric'
}).formatRange(date, new Date('01-16-1991')); // 'August 14, 1989 – January 16, 1991'

If the format isn't what we're hoping for, there's also a formatRangeToParts() function.

const rangeSpecialized = new Intl.DateTimeFormat('en', {
   month: 'long', 
   day: 'numeric', 
   year: 'numeric'
   }).formatRangeToParts(date, new Date('01-16-1991')).map(({type, value, source}) => {
       if (type === "day") {
           if (/1$/.test(value)) {
               return `${value}st`
           }
           if (/2$/.test(value)) {
               return `${value}nd`
           }
           if (/3$/.test(value)) {
               return `${value}rd`
           }
           return `${value}th`
       }
       if (source === 'shared') {
           return ' through ';
       }
       return value;
   }).join('') // 'August 14th, 1989 through January 16th, 1991'

STATIC METHODS

Date.UTC()

  • Uses universal time instead of local time
  • Returns a time value as a number instead of creating a Date object
  • Can be used to create a Date object with the date/time treated as UTC instead of local
const utcDate = new Date(Date.UTC(1989, 7, 14, 13, 21, 45, 0)) // 1989-08-14T13:21:45.000Z

Date.now()

Returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

Date.now()

Date.parse()

Parses the string representation of a date and returns the number of milliseconds since January 1, 1970 00:00:00 UTC.

const javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT'); // 818035920000

CONVERSIONS

Date to ISO string from year

const isoString = new Date('12-24-1995').toISOString(); // '1995-12-24T00:00:00.000Z'

Date to ISO String from date and time

const dateTime = new Date('2010-10-20 4:30').toISOString(); // '2010-10-20T04:30:00.000Z'

Date to JSON

const jsonDate = date.toJSON(); // 1989-08-14T13:21:45.000Z

Date to language-sensitive representation of date portion of date

Locales and options don't work in all browsers.

const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
date.toLocaleDateString('de-DE', options); // "Montag, 14. August 1989"

Date to language-sensitive representation of date

Locales and options are ignored in older implementations

const localeString = date.toLocaleString('en-GB', {timeZone: 'UTC'}); //  "14/08/1989, 13:21:45"

Date to language-sensitive representation of time portion of date

Locales and options not supported in all browsers

date.toLocaleTimeString('it-IT'); // "13:21:45"

Date to string

date.toString(); // 'Mon Aug 14 1989 13:21:45 GMT+0000 (Coordinated Universal Time)'

Date to time string

date.toTimeString(); // '13:21:45 GMT+0000 (Coordinated Universal Time)'

Date to UTC string

const date = new Date('08-14-1989 13:21:45 GMT-7:00');
date.toUTCString(); // "Mon, 14 Aug 1989 20:21:45 GMT"

Date to milliseconds since Unix Epoch

date.valueOf();  // 619104105000

Date to string or number (depending on arg)

// Date to string
date[Symbol.toPrimitive]('string');  // 'Mon Aug 14 1989 13:21:45 GMT+0000 (Coordinated Universal Time)'
// Date to number
date[Symbol.toPrimitive]('number');  // 619104105000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment