umma.dev

Dates and Times in Javascript

Date formats/ timestamps can be tricky to handle in JavaScript, especially when it comes to time zones. This post explains how I deal with converting timestamps and the libraries I use in React.

Date and Time Formats in JavaScript

Timestamps and dates can be manipulated in multiple ways, as outlined below.

Different Date Formats

new Date('2020-03-15')
new Date('03/15/2020')
new Date('2020/03/15')
new Date('2020/3/15')
new Date('March 15, 2020')
new Date('March 15, 2020 19:03:21')
new Date('2020-03-15 19:03:21')
new Date('2020-03-15T19:03:21')
new Date('15 March 2020')
new Date('15 Mar 2020')
new Date('15 March, 2020')
new Date('March 15, 2020')
new Date('March 15 2020')

// Timezones
new Date('March 15, 2020 19:03:21 (GMT)')

Converting Date and Timestamp Formats with Vanilla JavaScript

const date = new Date('March 15, 2020 19:03:21')

date.toString()
date.toTimeString()
date.toUTCString()
date.toDateString()
date.toLocaleString()
date.toLocaleTimeString()
date.getTime()

Using Packages to Handle Dates

Moment.js

Moment is a popular date/time library and is very easy to use. The only downside to using Moment in a react app is the size of the library.

Converting Unix Timestamp

const day = moment.unix(1318781876)

Formatting Timestamp to Date/Time

moment.unix(yourUnixEpochTime).format('dddd, MMMM Do, YYYY h:mm:ss A')

Date.fns

This a much smaller library and allows you to make over 180 different types of functions with dates and times.

Converting Unix Timestamp

import fromUnixTime from 'date-fns/fromUnixTime'

fromUnixTime(unixTime)

Formatting Timestamp to Date/Time

import format from 'date-fns/format'

format(date, format, [options])