JavaScript Date Object Simplified
Tags: javascript, codenewbie, tutorial, webdev
Published: 2021-07-05 18:46:31

You must have heard many times that **Objects represent real-world entities** when learning about object-oriented programming. I think the JavaScript Date object is a great testament to this statement. Because date and time are some of the most fundamental entities of the world.

**Date object in javascript represents a given point in time.** It has everything you can associate with time. For example day, year, month, hour, minutes...

Although this striking connection with our daily lives, `Date` in JavaScript remains one of the most complicated and thus, feared topics. So much so that we have to rely on external libraries like [Moment.js](https://momentjs.com/) for the simplest tasks.

In this post, I have tried to simplify the `Date` object as per my understanding and the most common functionalities I use in day-to-day development. Let us get started...

## Ways we can create the `Date` object

There are four ways we can create `Date` in JavaScript. All are useful in their own ways. Let us look at them one by one and when you will most likely use them.

### Using empty constructor

```jsx
const today = new Date();
console.log(today)
// Expected output: Tue Jun 29 2021 23:30:27 GMT+0530 (India Standard Time)
```

Using an empty constructor will create the current date and time. This is the most common way of creating a `Date` object. This will create the `Date` in the client's local timezone.

I generally use this way of creating the date when adding a new object. Like when creating a new TODO, I pass `createdDate` as a `new Date()`.

### Using milliseconds

```jsx
const someDate = new Date(1122334455);
console.log(someDate)
// Expected output: Wed Jan 14 1970 05:15:34 GMT+0530 (India Standard Time)
```

We can use the date constructor to create a Date object based on the number of milliseconds passed since Jan 1st of 1970 UTC+0. Jan 1st of 1970 UTC+0 is considered as **Unix Epoch Time.**

So if you pass `24 * 60 * 60 * 1000` (which is 24 hours in milliseconds), you will get the date as Jan 2nd of 1970 UTC+0.

In most cases, this is the standard way of creating `Date` because it is easier to communicate with the backend. When you want to save or retrieve dates, the backend prefers Unix Epoch Time.

### Passing each date entity separately

```jsx
const someDate = new Date(2020, 11, 12, 18, 12, 50);
console.log(someDate)
// Expected output: Sat Dec 12 2020 18:12:50 GMT+0530 (India Standard Time)
```

We can also create a `Date` object by passing individual values of year, month, day, hours, minutes, seconds, and milliseconds.

If we omit any values, the `Date` constructor will take the default values for those parameters.

I rarely use this method of creating the `Date` object. Because I would prefer passing milliseconds to the constructor most of the time.

*Note: `month` Integer value representing the month, beginning with 0 for January to 11 for December.*

### Passing the date string

```jsx
const someDate = new Date('2020-04-11T10:20:30Z')
console.log(someDate)
// Expected output: Sat Apr 11 2020 15:50:30 GMT+0530 (India Standard Time)
```

The date constructor also accepts a string as a parameter and creates a `Date` object by parsing the date string. This I feel is the most dangerous way of creating the date. Because we have to be careful of the format of the date string.

*Note: If you still want to use this method, as JavaScript officially supports a simplification of the ISO 8601 Extended Format, stick with `YYYY-MM-DDTHH:mm:ss.sssZ`.*

## Helpful methods in the `Date` object

Now that we know how to create the `Date` object, let us understand different methods on the date object. These common methods are useful in displaying dates or manipulating the dates. 

There are also some static methods on the date constructor that are used as shorthands for common tasks.

`getFullYear()` returns the year part from the date. With `setFullYear()` you can set the year part. Setting the year will not affect any other part of the date.

`getMonth()` returns month part from the date object. And with its counterpart `setMonth()` we can set the month in the date.

Similarly, `getDate()` returns the current date and `setDate()` sets the date in the date object.

```jsx
var someDate = new Date();
console.log(someDate);
// Expected Output: Wed Jun 30 2021 09:02:03 GMT+0530 (India Standard Time)

// Gets the day of the week
console.log(someDate.getDay());
// Expected Output: 3

console.log(someDate.getFullYear());
// Expected Output: 2021

console.log(someDate.getMonth());
// Expected Output: 5

console.log(someDate.getDate());
// Expected Output: 30

someDate.setFullYear(2020);
console.log(someDate);
// Expected Output: Tue Jun 30 2020 09:13:00 GMT+0530 (India Standard Time)

someDate.setMonth(6)
console.log(someDate);
// Expected Output: Thu Jul 30 2020 09:13:33 GMT+0530 (India Standard Time)

someDate.setDate(31);
console.log(someDate);
// Expected Output: Fri Jul 31 2020 09:13:55 GMT+0530 (India Standard Time)
```

Similarly, `getHours()`,  `setHours()`, `getMinutes()`, `setMinutes()`, `getSeconds()`, `setSeconds()`, `getMilliseconds()` and `setMilliseconds()` are used for getting and setting hours, minutes, seconds and milliseconds respectively.

## `Date.now()`

This method is used to get the current date and time as the number of milliseconds passed since Unix epoch time. The number of milliseconds returned by this method is referred to as the timestamp.

This is the most used method in my personal projects. This timestamp might even serve as id in some cases.

```jsx
var someDate = new Date();
console.log(someDate.getTime());
console.log(Date.now());
// Expected Output:
// 1625024936606
// 1625024936606

// Date.now() is same as saying someDate.getTime()
```

## Converting `Date` to another timezone

Most of us work on applications that are used by a global audience. And it is our duty as web developers to make our content accessible for all users. Localizing the date is a big part of this and it makes for a great user experience. This is why converting dates to different timezones is one of the common tasks we perform on the `Date` object.

Let us understand this through an example.

```jsx
const today = new Date(1625061658610);
const timeZone = 'America/New_York';
const dateOptions = {
  timeZone: timeZone,
  weekday: 'long',
  month: 'long',
  day: 'numeric',
  hour12: true,
  hour: '2-digit',
  minute: '2-digit'
};

console.log(today.toLocaleString("en-US", dateOptions)); 
// Expected output: Wednesday, June 30, 10:00 AM
```

If you want to read more about `Date.toLocalString()`, please check [this W3 School link](https://www.w3schools.com/jsref/jsref_tolocalestring.asp)

## Conclusion

Well, this is mostly all that we need to know about working with the JavaScript Date object. Of course, there is a lot more to it and I hope this basic understanding helps you to learn more complex stuff.

If you have anything more than what I have covered, comment down below. Until then, Happy Coding!!

*Photos by [Estée Janssens](https://unsplash.com/@esteejanssens?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)*

*This article was [originally published here](https://www.amitkhonde.com/blog/javascript-date-object-simplified). For more such interesting reads, [visit my blog](https://www.amitkhonde.com/blog).*