Working with Dates and Times in JavaScript
Tags: webdev, javascript, beginners, tutorial
Published: 2023-05-13 08:59:47

## 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!
<p>&nbsp;</p>
## Prerequisites

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

<p>&nbsp;</p>
## 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:

```jsx
let currentDate = new Date();

```

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 (`0`–`11`) on the specified date according to local time.

`getDate()`: Returns the day of the month (`1`–`31`) for the specified date according to local time.

 `getHours()`: Returns the hour (`0`–`23`) of the specified date according to local time.

`getMinutes()`: Returns the minutes (`0`–`59`) on the specified date according to local time.

`getSeconds()`: Returns the seconds (`0`–`59`) in the specified date according to local time.

`getMilliseconds()`: Returns the milliseconds (`0`–`999`) 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.
<p>&nbsp;</p>
## 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:

```jsx
toLocaleDateString()
toLocaleDateString(locales)
toLocaleDateString(locales, options)

```

An example of the above syntaxes include;

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

```

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

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

```

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

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

```

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

```jsx
toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
```

An example of the above syntaxes include:

```jsx
//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
```


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

```jsx
new Intl.DateTimeFormat()

```

An example of this syntax:

```jsx
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

```

Note that you must specify a time style when using this format to output time. Otherwise, the method returns a date.
<p>&nbsp;</p>
## 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](https://moment.github.io/luxon/#/) or [Moment.js](https://momentjs.com/), 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.

<p>&nbsp;</p>
## 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.
<p>&nbsp;</p>
## Credits

[Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat).

[W3 schools](https://www.w3schools.com/jsref/jsref_obj_date.asp)