# Mastering Dates: A Comprehensive Guide to Handling Dates in JavaScript

When working on any project, you will encounter various situations where you need to utilize dates in different forms. Sometimes, you need to retrieve the current date, while other times you may have to schedule a process for a specific time. Additionally, you might need to sort or retrieve data from a database using time or date as a filter. This short article aims to provide an overview of handling dates in JavaScript, particularly useful for beginners. Let's get started.

### Current Date and Time

So the first thing is how to get the current date and time using JavaScript? It's very simple as we have a built-in Date object for that- "**new Date()**". We only need to call it.

```javascript
let currentDate = new Date()
console.log(currentDate)

//OUTPUT
2024-02-19T16:32:30.069Z
```

### Current Year

Next is how to get the current year. For that we have a method which can be used along with Date object. It is "**getFullYear()**".

```javascript
const currentDate = new Date().getFullYear();
console.log(currentDate);

//OUTPUT
2024
```

### Current Month(0-11)

To fetch the current month we have a built-in method called "**getMonth()**", which can be used with Date object. Here you should know that this will return the present month index number and it starts with 0 for "January" and ends with 11 for "December". In real time it's February now, so if I use this method it will return 1, and if i have used this in last month, which is January, then it would have returned 0, and 2 for March and it goes on.

```javascript
const currentDate = new Date().getMonth();
console.log(currentDate);

//OUTPUT
1 // as it is February
```

If you want to return the current month in words, you can use like this;

```javascript
const months = [
 "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
]

const currentMonth = new Date().getMonth();
const monthInWords = months[currentMonth];
console.log(monthInWords);

//OUTPUT
February
```

### Current Date(1- 31)

If you want to get just the current day in number, you can use the "**getDate()"** method along with Date object. You will get a value between 1-31 based on which date is today.

```javascript
const currentDate = new Date().getDate();
console.log(currentDate);

//OUTPUT
19
```

### Current Day of the Week(0-6)

For that we use "**getDay()**" method. This will return a number between 0 to 6, where 0 indicates "Sunday" and 6 indicates "Saturday".

```javascript
const currentDate = new Date().getDate();
console.log(currentDate);

//OUTPUT
1 // as today is Monday
```

### Hours, Minutes, Seconds and Milliseconds

For fetching these you can use these methods respectively; **getHours(), getMinutes(), getSeconds(), getMilliseconds():**

```javascript
const currentDate = new Date().getHours();
console.log(currentDate);

//OUTPUT
22
```

### What is Date.now( ) ?

It is a static method of Date object. It returns current time in milliseconds. It actually returns number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC, according to the system clock.

```javascript
const currentDate = Date.now();
console.log(currentDate);

//OUTPUT
1708363554396
```

Usage: This provides a high-resolution timestamp that is useful for precise timing calculations.

### Date.UTC( ) - Important

When dealing with dates, sometimes we may encounter inaccuracies in time due to changes in local time zones. In such cases, you can use "**Date.UTC( )**" to retrieve the exact time, ensuring precision and consistency regardless of local time zone variations.

Before looking at the you need to understand what is UTC. You all might have heard about **GMT(Greenwich Mean Time)**. It is a time standard that is often used as a reference point for timekeeping.

* It is based on the mean solar time at the Prime Meridian (0° longitude) located in Greenwich, London, UK.
    
* Historically, GMT was used as the international civil time standard before being replaced by **Coordinated Universal Time (UTC)**.
    

So, UTC(Coordinated Universal Time) is a time standard that is essentially a successor to GMT. It is more precisely defined and does not vary with Earth's irregular rotation.

Now, let's write a code to fetch the first date of the current month using "**Date.UTC()**".

```javascript
const currentDate = new Date();
const firstDateOfMonth = new Date(Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), 1));
console.log(firstDateOfMonth);


//OUTPUT
2024-02-01T00:00:00.000Z
```

and if i write the same code without Date.UTC( ) for getting the first date of the month, then the output is like this.

```javascript
const currentDate = new Date();
const firstDateOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
console.log(firstDateOfMonth);

//OUTPUT
2024-01-31T18:30:00.000Z
```

There is a difference by some hours between two outputs.

### Formatting Dates

This is one of the most common requirements in almost all applications. When we fetch dates using the `Date` object, they typically come in the format 'YYYY-MM-DDTHH:mm:ss.sssZ'. However, in the user interface (UI) of our application, we often need to display dates in a more readable format. To achieve this, we can use date formatting.

1. ### **toLocaleDateString( )**
    
    If you want dates in this format "Monday, February 19, 2024" instead of "2024-02-19T16:32:30.069Z", we can use "**toLocaleDateString( )**" method. So, let's see how it works.
    
    So, in short it provides a way to format date according to the locale(*refers to a set of parameters that define the user's language, region, and cultural preferences in computing and software applications*) of the user's browser.
    

```javascript
//SYNTAX

const formattedDate = date.toLocaleDateString(locale, options);
```

* `locale`: It's optional. It's a string representing the locale used for formatting dates (e.g., "**en-US**" for **English** (United States), "**fr-FR**" for **French** (France)).
    
* `options`: It's also optional. It's an object containing options for formatting the date, such as `weekday`, `year`, `month`, `day`, `hour`, `minute`, `second`, `timeZone`, etc.
    

Now let's go in detail with examples.

```javascript
const currentDate = new Date();
const dateFormatted = currentDate.toLocaleDateString("en-US", {
  weekday: "long",
  day: "numeric",
  month: "long",
  year: "numeric",
});
console.log(dateFormatted);

//OUTPUT
Monday, February 19, 2024
```

1. ### **moment.js**
    
    This is a javaScript library which can be used for parsing, validating, manipulating, and formatting dates.
    

```javascript
//Before using Install it in the terminal using the following command
npm install moment

// AND INCLUDE USING moment.js
const moment = require('moment'); // this is for Node.js
```

Now, let's look at an example how we can format dates using moment.js

```javascript
const moment = require("moment");
const formattedDate = moment().format("MMMM Do YYYY, h:mm:ss a");
console.log(formattedDate);

//OUTPUT
February 19th 2024, 1:16:23 pm
```

Moment.js allows for extensive customization of date formatting using format strings. For example:

* `"MMMM"`: Month in full name
    
* `"Do"`: Day of the month with ordinal (e.g., "1st", "2nd", "3rd", etc.)
    
* `"YYYY"`: Full year
    
* `"h:mm:ss a"`: Hour, minutes, seconds, and AM/PM specification.
    

**Time Zone Customization**

In moment.js time zones can be customized using "**moment-timezone**" extension. This extension allows you to work with time zones and convert dates between different time zones.

```javascript
//Before using Install it in the terminal using the following command
npm install moment moment-timezone
```

Let's look at the syntax with an example

```javascript
const moment = require('moment');
require('moment-timezone');

// Create a Moment.js object
const date = moment();

// Display the current date and time in a specific time zone
const formattedDate = date.tz('America/New_York').format('YYYY-MM-DD HH:mm:ss');

console.log(formattedDate);

//OUTPUT
2024-02-19 03:29:48
```

### ISO Date

The ISO 8601 format is an internationally accepted standard for representing dates and times in a way that is easily readable and sortable. It was developed by the International Organization for Standardization (ISO).

The basic format for dates and times in ISO 8601 is as follows:

* **Date**: `YYYY-MM-DD` (e.g., 2024-02-19)
    
* **Time**: `HH:mm:ss` (e.g., 12:30:00)
    
* **Combined Date and Time**: `YYYY-MM-DDTHH:mm:ss` (e.g., 2024-02-19T12:30:00)
    

The extended format allows for more precision and includes additional components:

* **Date**: `YYYY-MM-DD` (e.g., 2024-02-19)
    
* **Time**: `HH:mm:ss.sss` (e.g., 12:30:00.000)
    
* **Time Zone Offset**: `±HH:mm` or `±HHmm` (e.g., +05:00, -0800)
    
* **Combined Date and Time with Time Zone Offset**: `YYYY-MM-DDTHH:mm:ss.sssZ±HH:mm` (e.g., 2024-02-19T12:30:00.000Z).
    

So, in short this is a standardized and efficient way to represent dates.

**Converting dates to ISO format.**

Sometimes, we need to convert dates into ISO String format in our projects or applications. So for that we use the "**toISOString( )**" method.

```javascript
const date= new Date();
const isoDate = date.toISOString();
console.log(isoDate);

//OUTPUT
2024-02-19T12:30:00.000Z
```

So these all are the main things I would like to explain in this article related to Dates in JavaScript.
