DATE OBJECT IN JAVASCRIPT

JSJavaScript Date Object allows us to work with dates:

const d = new Date();

//Thu Mar 03 2022 00:18:35 GMT+0100 (Ora standard dell’Europa centrale)

By default, JavaScript will use your browser’s time zone and display a date as a full text string.

CREATE DATE OBJECTS

Date objects are created with the new Date () constructor. There are 4 ways to create a new object date:

new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)

  1. new Date() create a new Date object with the current date and time:

const d = new Date();

Date objects are static. Computer time passes, Date objects do not.

  1. new Date(year, month, …) creates a new Date object with a specified date and time.

7 numbers specify the year, month, day, hour, minute, second and millisecond (in that order):

const d = new Date(2021, 11, 24, 10, 33, 30, 0);

// Fri Dec 24 2021 10:33:30 GMT+0100 (Ora standard dell’Europa centrale)

Note: JavaScript counts months from 0 to 11: January = 0, December = 11.

Specifying a month greater than 11 will not cause an error but will add the overflow to the following year:

Or:

const d = new Date(2018, 15, 24, 10, 33, 30);

Equivalent to:

//Wed Apr 24 2019 10:33:30 GMT+0200 (Ora legale dell’Europa centrale)

Specifying a day greater than max will not cause an error but will add the overflow to the next month:

Specifying:

const d = new Date(2018, 5, 35, 10, 33, 30);

you will have:

// Thu Jul 05 2018 10:33:30 GMT+0200 (Ora legale dell’Europa centrale)

USE 6,4,3 OR 2 NUMBERS

    • 6 numbers specify the year, month, day, hour, minute, second.
    • 5 numbers specify the year, month, day, hour and minute.
    • 4 numbers specify the year, month, day and time.
    • 3 numbers specify the year, month and day.
    • 2 numbers specify the year and month.
      You cannot omit the month. If you provide only one parameter, it will be treated as milliseconds.

const d = new Date(2021);

// Thu Jan 01 1970 01:00:02 GMT+0100 (Ora standard dell’Europa centrale)

PREVIOUS CENTURY

One-and two-digit years will be interpreted as 19xx:

const d = new Date(99, 11, 24);

// Fri Dec 24 1999 00:00:00 GMT+0100 (Ora standard dell’Europa centrale)

const d = new Date(9, 11, 24);

// Fri Dec 24 1909 00:00:00 GMT+0100 (Ora standard dell’Europa centrale)

  1. new Date(dateString) create a new Date object from a string:

const d = new Date(“October 15, 2021 11:13:00”);

// Fri Oct 15 2021 11:13:00 GMT+0200 (Ora legale dell’Europa centrale)

JAVASCRIPT STORES DATES AS MILLISECONDS

JavaScript stores dates as a number of milliseconds since January 01, 1970, 00:00:00 UTC (Universal Time Coordinated). Zero time is January 01, 1970 00:00:00 UTC. Now the time is: 1646262963669 milliseconds after January 01, 1970

  1. new Date(milliseconds) create a new Date object as zero time plus milliseconds:

const d = new Date(100000000000);

// Sat Mar 03 1973 10:46:40 GMT+0100 (Ora standard dell’Europa centrale)

const d = new Date(-100000000000);

// Mon Oct 31 1966 15:13:20 GMT+0100 (Ora standard dell’Europa centrale)

DATE INPUT

There are generally 3 types of JavaScript date input formats:

Date input

The ISO format follows a strict standard in JavaScript. The other formats are not as well defined and may be browser specific.

DATA OUTPUT

Regardless of the input format, JavaScript will (by default) generate dates in full text string format:

Thu Mar 03 2022 10:34:35 GMT+0100 (Ora standard dell’Europa centrale)

ISO DATES

ISO 8601 is the international standard for the representation of dates and times. ISO 8601 syntax (YYYY-MM-DD) is also the default JavaScript date format:

const d = new Date(“2015-03-25”);

The calculated date will be relative to your time zone. Depending on your time zone, the above result varies between March 24 and March 25. ISO dates can be written without specifying the day (YYYY-MM):

const d = new Date(“2015-03”);

The result will vary between February 28 and March 01 depending on the time zone. ISO dates can be written without month and day (YYYY):

const d = new Date(“2015”);

The time zones will vary the result between December 31st 2014 and January 1st 2015.

ISO DATE (DATE AND TIME)

Dates can be written by adding hours, minutes and seconds (YYYY-MM-DDTHH:MM:SSZ):

const d = new Date(“2015-03-25T12:00:00Z”);

Date and time are separated by a capital T. UTC time is defined with a capital Z. If you want to change the time relative to UTC, remove the Z and add  +HH: MM or -HH: MM:

const d = new Date(“2015-03-25T12:00:00-06:30”);

UTC (Universal Time Coordinated) is the same as GMT (Greenwich Mean Time). Omitting T or Z in a date and time string can give different results in different browsers.

TIME ZONES

When setting a date, without specifying the time zone, JavaScript will use the browser’s time zone. When a date is obtained, without specifying the time zone, the result is converted to the browser’s time zone. In other words: If a date/time is created in Greenwich Mean Time (GMT), the date/time will be converted to Central US Daylight Time (CDT) if a user navigates from the central United States.

SHORT DATES

Short dates are written with a “MM/DD/YYYY” syntax like this:

const d = new Date(“03/25/2015”);

WARNING!

In some browsers, months or days without leading zeros can produce an error:

const d = new Date(“2015-3-25”);

The behavior of “YYYY/MM/DD” is not defined. Some browsers will try to guess the format. Some will return NaN.

const d = new Date(“2015/03/25”);

The behavior of “DD-MM-YYYY” is also undefined. Some browsers will try to guess the format. Some will return NaN.

const d = new Date(“25-03-2015”);

LONG DATES

Long dates are often written with a syntax like this “MMM DD YYYY”:

const d = new Date(“Mar 25 2015”);

Month and day can be in any order, and the month can be written in full (January) or abbreviated (Jan), commas are ignored. Names are not case sensitive:

const d = new Date(“JANUARY, 25, 2015”);

PARSING DATES

If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds. Date.parse() returns the number of milliseconds between the date and January 1, 1970: You can then use the number of milliseconds to convert it to a Date object.

let msec = Date.parse(“March 21, 2012”);
const d = new Date(msec);

GET DATE METHODS

Method Get Date
Method UTC

METODI SET DATES

Set dates
Copy to Clipboard

DEEPENING AI

In JavaScript, the Date object is used to work with dates and times. It provides various methods for getting and setting the time, date, and managing time zones. A detailed description follows:

Creating a Date Object

You can create a new Date object using the Date() constructor. There are several ways to create a Date object:

1. Current Date (without parameters):

const dataCorrente = new Date();
console.log(dataCorrente);

Returns the current system date and time.

2. Date with a specific string (passing a string in the accepted format):

const dataDaStringa = new Date(“2024-09-15“);
console.log(dataDaStringa);

You can pass a string representing a date. The common format is YYYY-MM-DD, but it also supports more complex formats.

3. Date with numeric parameters (year, month, day, hour, minutes, seconds, milliseconds):

const dataSpecifica = new Date(2024, 8, 15, 12, 30, 0);
console.log(dataSpecifica);

Months are indexed by 0 (January = 0, February = 1, etc.), so 8 represents September.

4. With milliseconds since epoch (January 1, 1970):

const dataDaMillisecondi = new Date(1633024800000);
console.log(dataDaMillisecondi);

The value passed is the number of milliseconds elapsed since the Unix epoch.

Useful methods for time operations

-getTime(): Returns the milliseconds since the epoch (January 1, 1970).

const millisecondi = dataCorrente.getTime();
console.log(millisecondi);

-setTime(milliseconds): Sets the date using the millisecond value from the epoch.

dataCorrente.setTime(1609459200000); // 1 gennaio 2021

-Date.now(): Returns the current timestamp in milliseconds from the epoch.

const oraCorrente = Date.now();
console.log(oraCorrente);

-toLocalDateString(): Returns the date formatted according to the specified locale (language and country).

const dataLocale = dataCorrente.toLocaleDateString(“it-IT“);
console.log(dataLocale);

Compare Dates

You can compare Date objects by comparing their timestamps:

-Check if one date is before another:

const data1 = new Date(“2024-01-01“);
const data2 = new Date(“2024-12-31“);
console.log(data1 < data2); // true

-Check whether two dates are the same (timestamp comparison):

const data1 = new Date(“2024-01-01“);
const data2 = new Date(“2024-01-01“);
console.log(data1.getTime() === data2.getTime()); // true

Full example

const oggi = new Date();
console.log(“Oggi:“, oggi);

const dataSpecifica = new Date(2024, 8, 15, 12, 30, 0);
console.log(“Data specifica:“, dataSpecifica);

const differenzaInMillisecondi = oggi.getTime() – dataSpecifica.getTime();
const differenzaInGiorni = differenzaInMillisecondi / (1000 * 60 * 60 * 24);
console.log(“Differenza in giorni:“, differenzaInGiorni);

Conclusion

The Date object in JavaScript is powerful and offers many features for handling dates and times. It is essential to know the supported methods and formats to properly manipulate dates in your code.

LINKS TO PREVIOUS POST

THE JAVASCRIPT LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB