How to format Date and Time in Javascript

Let’s explore the moment.js alternative in Javascript
Nov 7 2022 · 4 min read

Background

In one of our laravel projects, after upgrading dependencies, the docker build suddenly started throwing an error of moment.js.

On debugging, I noticed that moment.js was now in maintenance mode and recommends to use of different libraries as an alternative.

As our requirements for date and time are not much complex, we decided to use javascript’s default Date() object and comes up with this article.

If you are finding some readymade solutions for date and time utilities, this article is for you.

Let’s build date and time solutions…

We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out Justly and start building your habits today!
 

What you will learn?

  • Get the year, month, date, day, and time
  • First and Last day of the month
  • Add and Subtract day, month, year, time
  • Get and Set the timezone for the date
  • Get dates in various formats

Introduction

Date() is an object of javascript that contains all date and time properties as below,

new Date(year, month, day, hours, minutes, seconds, milliseconds);

We can get currentDate as,

const cDate = new Date();

Internationalize API(Intl) is very useful for date and time utility conversion.

1. Get the year, month, date, day, and time

Starting with easy conversions, we will retrieve the year, month, date, day, and milliseconds of the current date.

/** year **/

// Current year : 2022
console.log("Current year : ", new Date().getFullYear())

// Given date year : 2018
console.log("Given date year : ", new Date("2018-03-25").getFullYear())

/** 
   month 
   getMonth() starts with 0, it will returns currentMonth - 1 number (11 - 1 = 10).
**/

// Current month : 10 
console.log("Current month : ", new Date().getMonth())

// Given date month : 2
console.log("Given date month : ", new Date("2018-03-25").getMonth())

// Full month name : November
// For short name, can use 'short'
console.log("Full month name : ", cDate.toLocaleString('default', { month: 'long' }))

/** date **/

// Current date : 7
console.log("Current date : ", new Date().getDate())

// Given date's date : 25
console.log("Given date's date : ", new Date("2018-03-25").getDate())

/** weekday **/

// Today's weekday : 1 (monday)
console.log("Today's weekday : ", new Date().getDay())

// Given date weekday : 0 (sunday)
console.log("Given date's date : ", new Date("2018-03-25").getDay())

/** millis **/

// Current time in millis : 1667813042954
console.log("Current time in millis : ", Date.now())

Similarly, it allows us to set all the properties as well on a given date using setFullYear(), setMonth(), setDate(), etc…

2. First day of the month

For the first day of the month, just set the year and month.

// Tue Nov 01 2022 00:00:00 GMT+0530 (India Standard Time)

const date = new Date(cDate.getFullYear(), cDate.getMonth());
console.log(date)

3. Last day of the month

For the first day of the month, add 1 to month (which denotes next month) and the date as 0.

// Wed Nov 30 2022 00:00:00 GMT+0530 (India Standard Time)

const date = new Date(cDate.getFullYear(), cDate.getMonth() + 1, 0);
console.log(date)

4. Add day, month, year, time

We have explored set methods of given Date to achieve this as below,

// Current date in millis : 1667813042954

// A year after : 1699353114157
console.log("A year after : ", new Date().setYear(cDate.getFullYear() + 1))

// 3 months after : 1675765990138
console.log("3 months after : ", new Date().setMonth(cDate.getMonth() + 3))

// 2 days after : 1667990027784
console.log("2 days after : ", new Date().setDate(cDate.getDate() + 2))

// 2 hours after : 1667824456277
console.log("2 hours after : ", new Date().setHours(cDate.getHours() + 2))

// 5 minutes after : 1667817585028
console.log("5 minutes after : ", new Date().setMinutes(cDate.getMinutes() + 5))

5. Subtract day, month, year, time

Similarly, we can perform subtraction on a given date.

// Current date in millis : 1667813042954

// A year ago : 1636280463554
console.log("A year ago : ", new Date().setYear(cDate.getFullYear() - 1))

// 3 months ago : 1659867711241
console.log("3 months ago : ", new Date().setMonth(cDate.getMonth() - 3))

// 2 days ago : 1667643213795
console.log("2 days ago : ", new Date().setDate(cDate.getDate() - 2))

// 2 hours ago : 1667809705405
console.log("2 hours ago : ", new Date().setHours(cDate.getHours() - 2))

// 5 minutes ago : 1667816708972
console.log("5 minutes ago : ", new Date().setMinutes(cDate.getMinutes() - 5))

6. Get and Set the timezone

You can easily get the current timezone using Intl’s resolvedOptions.

Intl.DateTimeFormat().resolvedOptions().timeZone

You can get a cDate or any given date in the given timezone.

cDate.toLocaleString('en-US', {
    timeZone: 'your timezone',
}),

The final code will be,


// Current timezone is :  Asia/Calcutta
console.log("Current timezone is : " , Intl.DateTimeFormat().resolvedOptions().timeZone)

// Current date in America/Los_Angeles : 11/7/2022, 2:59:43 AM
console.log("Current timezone is : " , cDate.toLocaleString("en-US", { timeZone: "America/Los_Angeles" }))

7. Get dates in various formats

We will use the toLocaleString() method implemented with Intl.DateTimeFormat API support.

// Hours of date in 12 hours format (ha) : 5 pm
console.log(cDate.toLocaleString("default", { hour: "numeric",  hour12: true }))

// MMM : Nov
console.log(cDate.toLocaleString('default', { month: 'short' })

// MMM YY : Nov 22
console.log(cDate.toLocaleString('default', { month: 'short', year: '2-digit' })

// DD MMM YY : 07 Nov 22
console.log(cDate.toLocaleString('default', { day:'2-digit', month: 'short', year: '2-digit' })

// YYYY-MM-DDT00:00 : 2022-11-07T00:00
console.log(cDate.toISOString().split("T")[0] + "T00:00")

// MMM DD, YYYY : Nov 07, 2022
console.log(cDate.toLocaleString('en-US', { day:'2-digit', month: 'short', year: 'numeric' }))

// 07 November 2022
console.log(cDate.toLocaleString('default', { day:'2-digit', month: 'long', year: 'numeric' }))

// dd/MM/yyyy h:mm a : 07/11/2022, 5:32 pm
console.log(cDate.toLocaleString('default', { day:'2-digit', month: '2-digit', year: 'numeric' , hour: "numeric", minute: "numeric", hour12: true}))

Code, Build, Repeat.
Stay updated with the latest trends and tutorials in Android, iOS, and web development.
sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.
sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.
canopas-logo
We build products that customers can't help but love!
Get in touch
contact-footer
Say Hello!
footer
Follow us on
2024 Canopas Software LLP. All rights reserved.