JavaScript — DateTime

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

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

Ref

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:)