DEV Community

Cover image for Working with Dates and Times in JavaScript
Ghloriey
Ghloriey

Posted on

Working with Dates and Times in JavaScript

Introduction

Are you a beginner in JavaScript looking to work with dates and times? Look no further! This article will guide you through creating and manipulating dates using the built-in Date object in JavaScript.

Discover how to establish a new date object, filter individual components like the year and month, and format dates for your website or app. In addition, we'll discuss some common pitfalls to avoid while working with dates and times.

By the end of this article, you'll have an excellent foundation on using dates and times in JavaScript, and you'll be able to use that understanding to build dynamic, time-based web app. So let's get started!

 

Prerequisites

  • Basic knowledge of Javascript, including declaring variables and JavaScript objects.
  • A code editor such as; Visual Studio Code or Sublime.

 

The Date object

Dates and times are represented in JavaScript using the built-in Date object. A new date object is created by calling the Date() constructor with no arguments, like this:

let currentDate = new Date();

Enter fullscreen mode Exit fullscreen mode

It provides several methods for managing, manipulating, and formatting dates and times. There are two main methods of the Date object;

get Methods

It retrieves or gets date and time information such as the month, year, hour or minutes. The commonly used get methods in Date objects include: 

getfullYear(): Returns the year (4 digits for 4-digit years) of the specified date according to local time.

getMonth(): Returns the month (011) on the specified date according to local time.

getDate(): Returns the day of the month (131) for the specified date according to local time.

 getHours(): Returns the hour (023) of the specified date according to local time.

getMinutes(): Returns the minutes (059) on the specified date according to local time.

getSeconds(): Returns the seconds (059) in the specified date according to local time.

getMilliseconds(): Returns the milliseconds (0999) in the specified date according to local time.

getTime(): Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)

 geTimeZoneoffSet(): Returns the time-zone offset in minutes for the current locale.

set Methods

As the name implies, the set method changes or set an object's value. The commonly used set methods include;

setfullYear(): Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.

setMonth(): Sets the month for a specified date according to local time.

setDate(): Sets the day of the month for a specified date according to local time.

setHours(): Sets the hours for a specified date according to local time.

setMinutes(): Sets the minutes for a specified date according to local time.

setSeconds(): Sets the seconds for a specified date according to local time.

setMilliseconds(): Sets the milliseconds for a specified date according to local time.

setTime(): Sets the Date object to the time represented by several milliseconds since January 1, 1970, 00:00:00 UTC. Use negative numbers for times prior.

 

How to Format Date and Time in JavaScript

Two methods are used to format dates and times in JavaScript. This includes:

1. The toLocaleDateString()/toLocaleTimeString() format:

The arguments that can be passed in this format include the locale and the options.

The syntax for toLocaleDateString() in this format is:

toLocaleDateString()
toLocaleDateString(locales)
toLocaleDateString(locales, options)

Enter fullscreen mode Exit fullscreen mode

An example of the above syntaxes include;

let currentDate = new Date()
alert(currentDate.toLocaleDateString())//output 07/05/2023

Enter fullscreen mode Exit fullscreen mode

When this format is used without an argument, the output is based on the implementation, the default locale, and the default time zone.

let currentDate = new Date()
alert(currentDate.toLocaleDateString("en-CA"))// output 2023-05-07

Enter fullscreen mode Exit fullscreen mode

When a particular locale is passed in the argument, the output format is based on that locale.

let currentDate = new Date()
alert(currentDate.toLocaleDateString("en-CA",{dateStyle: "long"}))
// output May 7, 2023

Enter fullscreen mode Exit fullscreen mode

When a particular locale is passed in the argument, and various options are specified, the output is based on both the locale and the specified options.

The  syntax for toLocaleTimeString() format is:

toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
Enter fullscreen mode Exit fullscreen mode

An example of the above syntaxes include:

//Without an argument
let currentDate = new Date()
alert(currentDate.toLocaleTimeString());//output 13:28:05

// with locale as the only argument
let currentDate = new Date()
alert(currentDate.toLocaleTimeString('en-US'));//output 1:29:40 PM

// with locale as the only argument
let currentDate = new Date()
alert(currentDate.toLocaleTimeString('en-US'));//output 1:29:40 PM
Enter fullscreen mode Exit fullscreen mode

2. The  Intl.DateTimeFormat format:

This format is similar to the first because it can be with or without an argument, and the arguments that it accepts are also the locale and the options.

The syntax for this format is:

new Intl.DateTimeFormat()

Enter fullscreen mode Exit fullscreen mode

An example of this syntax:

let currentDate = new Date()
alert(new Intl.DateTimeFormat('en-US', {dateStyle: "full"}).format(currentDate));// output Sunday, May 7, 2023

let currentDate = new Date()
alert (new Intl.DateTimeFormat('en-US', {timeStyle: "full"}).format(currentDate));// output 1:46:48 PM West Africa Standard Time

Enter fullscreen mode Exit fullscreen mode

Note that you must specify a time style when using this format to output time. Otherwise, the method returns a date.

 

Best Practices for Working with Dates and Time

  1. Remember performance: Creating new Date objects can be expensive when repeatedly manipulating dates, so you can use existing date objects whenever you can to improve speed.
  2. JavaScript uses the local timezone of the computer to handle timezones. If you have to work with various time zones, consider using a package like Luxon or Moment.js, which offer more powerful timezone management.
  3. Use the JavaScript date object: The built-in Date object in JavaScript is available to manage dates and timings. It is advised because it provides numerous ways to format and manipulate dates.
  4. Always check that user input for times and dates is accurate and within the desired range. Doing so helps avoid bugs brought on by improper data inputs.

 

Conclusion

If you've followed this article from the beginning, then congratulations! You have learned the basics of working with dates and times in JavaScript. Using the built-in Date object, you can create and manipulate dates to display in your web app.

Working with dates and timing should follow best practices to ensure the accuracy of your data. A library like Moment.js makes manipulating dates and times easier if you searching for more sophisticated capabilities and functionality.

 

Credits

Mozilla Developer Network.

W3 schools

Top comments (0)