JavaScript — DateTime

Toddypet
3 min readJan 24, 2021

Recently I am working on an app that required me to compare the DateTime data from API between my local pc time. Below I have listed out some useful method that I always use to help me compare and present the right time

Get local time

By default, when you are setting up a new Date Object, it will return a date object with your browser's time

After creating a Date object, you can use below method to get the data you need

Ref: https://www.w3schools.com/js/js_date_methods.asp

However, when you are developing an application, it's a common procedure that you will save and send the date in UTC time to support users in any timezone. In this case, you just need to specify UTC in your method, for example, getUTCTime()

Compate time

By using Date object, you can only use operator > , < , ≥, ≤. It doesn’t accept ===, == operator

A common approach we use in javascript is to convert it into million-second value and then compare two values. You can either use .getTime() or Date.parse(). It will return the same result

Convert date to local timestamp format

While reading in a Date object, you can use .tolocalString Intl.DateTimeFormat object to convert it into the datetime format in your locals.

  1. Date object api

The easiest way is to call the api .Below provide some example to show different type of api you can use

2. Intl.DateTimeFormat

//first create a new date object
const date = new Date();
//convert the date object into Intel.DateTimeFormat object. without specifying any set up, it will format with local language. console.log(new Intl.DateTimeFormat.format(date))
//specify date format, you can format it with assgined language
console.log('format ir in US', new Intl.DateTimeFormat('en-US).format(date))
//add an option (object) to specify the format you want to present
const options = {
hour: 'numeric', minute:'numeric', second:'numeric',
timeZone: 'UTC',
timeZoneName: 'short'
}
console.log(new Intl.DateTimeFormat('en-GB', options).format(date))

Ref

--

--

Toddypet

Hello, I am Heidi. I started this medium blog to post all of the note I have when I am learning new things. Hope you find it useful as well:)