Date and Time

Date and Time

Date and Time


In JavaScript, there is a built-in object Date for handling all the date and time-related operations. For instance, you can use it for displaying the current date and time, creating a calendar, build a timer, and much more.

How to Create a Date Object

To learn how to create a new Date object, follow the steps below.

Note that the new operator is generally used to create a date object.

Call new Date () choosing one of the following arguments:

new Date()

You can create a Date object for the current date and time without arguments like this:

let nowDate = new Date();

console.log(nowDate); // shows current date/time

This action returns the current date with the time and time zone.

We can distinguish other ways of creating a Date using the new operator.

New Date with Milliseconds

Creating a Date object with the time equal to the number of milliseconds passed after the January 1st, 1970 UTC+0.

Here is an example:

// 0 means 01.01.1970 UTC+0

let startDate = new Date(0);

console.log(startDate);

// now add 24 hours, get 02.01.1970 UTC+0

let startTime = new Date(24 * 3600 * 1000);

console.log(startTime);

In this example, a timestamp is used to represent the number of milliseconds passed since the beginning of 1970.

Creating Date Object Using dateString

It is possible to create a Date object by parsing the date string representation. The string representation will be accepted in case it can be parsed using Date.parse().

Here is an example:

let date = new Date("2019-12-26");

console.log(date);

//The isn't a fixed time, so it's expected to be midnight GMT and

// is modified according to the timezone, in which the code is run

// So the result could be

// Thu Dec 26 2019 04:00:00 GMT+1100 (Australian Eastern Daylight Time)

The following format is acceptable: new Date(year, month, date, hours, minutes, seconds, ms). You should also follow these rules:

  • The year should consist of four digits ( for example, 2020);
  • The counting of the month must start from 0 (For example, 0 is January and 11 in December);
  • The day of the month is the date parameter; if it is absent, you should assume 1.
  • In case hours/minutes/seconds/ms is absent, you should assume them to be equal 0.

For example:

new Date(2019, 0, 1, 0, 0, 0, 0); // 1 Jan 2019, 00:00:00
new Date(2019, 0, 1); // the same, hours etc are 0 by default

Minimal precision should be one millisecond.

For instance:

let date = new Date(2019, 0, 1, 2, 3, 4, 567);

console.log(date); // 1.01.2019, 01:02:04.567

Accessing Date Components

Now, we will discover ways of accessing data components. Here they are:

getFullYear()

getting the year ( should be of 4 digits).

getMonth()

getting the month ( from 0 to 11).

getDate()

getting the day of a month ( from 1 to 31).

getHours(),
 getMinutes(),
 getSeconds(),
 getMilliseconds()

getting the appropriate time components.

It is essential to use getFullYear(), not getYear(), as the latter deprecated and can return 2-digit year at times. So, you’d better never use it in your practice.

Besides, it is possible even to get a weekday by calling:

getDay()

It will allow you to get a weekday from Sunday 0 to Saturday 6.

How to Set Date Components

In JavaScript, several methods are used for setting the date and time components. Among them are:

setFullYear(year, [month], [date])
setMonth(month, [date])
setDate(date)
setHours(hour, [min], [sec], [ms])
setMinutes(min, [sec], [ms])

Some methods are capable of setting multiple components simultaneously. For instance, setHours.

Here is an example:

let today = new Date();

today.setHours(0);

console.log(today); // still today, but the hour is changed to 0

today.setHours(0, 0, 0, 0);

console.log(today); // still today, now 00:00:00 sharp.

Autocorrection

A handy feature of Date objects is autocorrection. You can set values that are out of range, and it will adjust them automatically.

For example:

let date = new Date(2019, 6, 32); // 32 Jul 2019 

console.log(date); // 1st Aug 2019!

Date to Number, Date Diff

Whenever you convert a Date to number, it is transformed into the timestamp, like date.getTime().

Let’s consider the following example:

let msDate = new Date(); 

console.log(+msDate); // it's a same as date.getTime(), it's  the number of milliseconds

It is also important to note that dates can be subtracted. You can use it for measurements, as follows:

let startDate = new Date(); // start measuring time 

for (let x = 0; x < 10000; x++) {

  let smth = x * x * x;

}

let endDate = new Date(); // end measuring time

console.log(`The loop took ${endDate - startDate} ms`);

Date.now()

If you decide to measure time, it is not necessary to use the Date object. You can use Date.now(), which will return the current timestamp.

For instance:

let startDate = Date.now(); // milliseconds count from 1 Jan 1970 

for (let x = 0; x < 10000; x++) {

  let doSomething = x * x * x;

}

let endDate = Date.now(); 

console.log(`The loop took ${endDate - startDate} ms`);

Date.parse From a String

If you want to read a date from a string, the Date.parse(str) will help you. The format of the string must be: MM-DDTHH:mm:ss.sssZ. Several shorter options are also possible: YYYY-MM-DD or YYYY-MM or even YYYY.

Here is an example of the usage of Date.parse(str):

let ms = Date.parse('2019-02-28T14:52:20.254-08:00');

console.log(ms); // 1551394350254, it’s a timestamp

new Date can be instantly created from the timestamp, like this:

let date = new Date(Date.parse('2019-02-28T14:52:20.254-08:00'));

console.log(date);

Summary

In JavaScript, the Date object is used for representing date and time. The Date object includes both of them. As a rule, the months are counted starting from zero and ending with 11. The weekdays are also counted starting from zero. In JavaScript, the dates might be subtracted and give their difference in milliseconds, as a Date is transformed into timestamp when converted to a number. Finally, unlike other systems, in JavaScript, timestamps are in milliseconds, not seconds.

Reactions

Post a Comment

0 Comments

close