Date and Time in JavaScript | Part 1

Introduction

Date and time are the most significant part of our daily lives. We may need to create a website with a calendar in JavaScript. These applications may need to display time-based on the user's current different time zones.

The built-in date object and related methods in JavaScript help us to achieve all of these goals.

In this article, we are going to learn the date and time in JavaScript. So, without any further ado, let's get started!

The Date Object

The Date object in JavaScript is used to represent date and time. We can work with dates and times using the date object. We can’t create only a date or only time alone. Both are always present in date objects together. With new Date(), date objects are created.

Date Creation Methods

There are four different types of methods for the creation of date and time:

1. new Date()

When no argument is present, it creates a Date object for the current date and time. It gives the current date and time as an output.

let present = new Date();
alert(present); 

2. new Date(milliseconds)

It creates a date object with a time value equal to many milliseconds since January 1, 1970, UTC+0, or we can say it creates a new date object as January 1, 1970, 00:00:00 UTC plus the milliseconds.

Zero time refers to January 01, 1970, 00:00:00 UTC.

// 0 refers to 01.01.1970 UTC+0
let jan = new Date(0);
alert( jan );
// adding 24 hours, get 02.01.1970 UTC+0
let jan = new Date(24 * 3600 * 1000);
alert( jan );

A timestamp is an integer number representing the number of milliseconds that have passed since 1970 began. It's a numeric representation of a date. We can always use the new Date(timestamp) method to create a date from a timestamp and convert an existing Date object to a timestamp using date.getTime().

Dates before January 1, 1970, have negative timestamps, for example:

//For date 31 Dec 1969
let dec = new Date(-24 * 3600 * 1000);
alert( dec );

3. new Date(datestring)

It creates a date from the string of dates. If there is only one argument, and if it is a string, then it is parsed automatically. 

let date = new Date("2021-11-26");
alert(date);
// Because the time isn't specified
// it's assumed to be midnight GMT
// adjusted for the timezone
// in which the code is executed. 

4. new Date(year, month, date, hours, minutes, seconds, milliseconds)

It creates a date in the local time zone using the specified components. The first two arguments are mandatory.

The year must be four digits long: 2021 is acceptable, but 21 is not.

The month count goes from 0 (for January) to 11 (for December).

The date argument is the month's day; if it isn't present, 1 is assumed.

Hours/minutes/seconds/ms are presumed to be equal to 0 if they are not present.

Example:

new Date(2021, 0, 1, 0, 0, 0, 0); // 1 Jan 2021, 00:00:00
new Date(2021, 0, 1); 

The maximal precision is 1 ms:

let date = new Date(2021, 0, 1, 2, 3, 4, 567);
alert( date ); // 1.01.2021, 02:03:04.567

 

The table below contains the descriptions of all of the parameters shown in the above syntax:

ParametersDescriptions
dayIt refers to the day of the month by an integer value. This parameter can be avoided.
dateStringIt signifies a date format string.
hoursIt refers to the hour of the day represented by an integer value. This parameter can be avoided.
millisecondsIt refers to the millisecond of a time represented by an integer value. This parameter can be avoided.
minutesIt refers to the minute of a time represented by an integer value. This parameter can be avoided.
monthIt is represented by integer values which range from 0 (for January) to 11 (for December).
secondIt refers to the second of a time represented by an integer value. This parameter can be avoided.
valueIt refers to the number of milliseconds since January 1, 1970, 00:00:00 UTC.
yearIt is represented by integer values that range from the years 1900 to 1999.

If no parameter is specified, the current date and time are returned.

Accessing the Date with get

We can use numerous built-in methods to retrieve all of the date's components. Each of these methods begins with the get and returns the date relative to the local timezone.

The get methods of the Date object are listed in detail below:

DateMethodRange
YeargetFullYear()YYYY
MonthgetMonth()0-11
Day(month)getDate()1-31
Day(week)getDay()0-6
Hour getHours()0-23
MinutegetMinutes()0-59
SecondgetSeconds()0-59
MillisecondgetMilliseconds()0-999
TimestampgetTime()In milliseconds since the epoch time.

Let's create a new date and assign it to a variable based on July 31, 1980.

// Initializing a party date
const party = new Date(1980, 6, 31);

 

All of our techniques can now be used to obtain date component, from year to millisecond.

party.getFullYear();      // 1980
party.getMonth();         // 6
party.getDate();          // 31
party.getDay();           // 4
party.getHours();         // 0
party.getMinutes();       // 0
party.getSeconds();       // 0
party.getMilliseconds();  // 0
party.getTime();          // 333849600000 (GMT)

 

Sometimes, we may need to extract only a portion of a date. The built-in get methods help us to extract a portion of date.

For example, we can compare the current date to the day and month of June 25th to see if it's June 25th or not.

// Get today's date
const today = new Date();
// Compare today with June 25th.
if (today.getDate() === 25 && today.getMonth() === 5) {
 console.log("June 25th");
} else {
 console.log("Not June 25th");
}

Output: 

Not June 25th

The built-in date methods that start with the get method allow us to access date components that return the number associated with the created object.

Frequently Asked Questions

 

Q1) In a date object, how does JavaScript store dates?

Answer: Dates are stored in milliseconds in JavaScript. Since January 1, 1970, 00:00:00 UTC, JavaScript stores dates as a number of milliseconds.

 

Q2) What is the date object in JavaScript?

Answer: The Date object is a built-in datatype in the JavaScript programming language. It's a tool for calculating dates and times. The new Date(), is used to create the Date object. The Date object can be used to calculate date and time with millisecond precision.

 

Q3) In JavaScript, how do we check if a date is valid?

Answer: First, we have to store the date object in a variable. If the date is correct, getTime() will always return the same value. If the date is invalid, getTime() will return NaN. The isValid() function determines whether the getTime() method is equal to itself or not.

Key Takeaways

In this article, we've learned about the JavaScript date and time creation method and how we can access it using the get method. If you want to get a firm grasp on the subject more, you must read our next article on date and time in JavaScript. 

If you want to learn advanced front-end web development, Coding Ninjas has one of the best courses available, which you can find here

 

Thank you for reading!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think