Different ways to create a new date object in Java Script

Java Script @ Freshers.in

In JavaScript, there are several ways to create a new Date object:

Default Constructor: Creates a new Date object with the current date and time.

let now = new Date();

Date String: Constructs a Date object using a date string.

let dateStr = new Date("2023-12-01");

Date Components: Specifies year, month, and day to create a specific date. The month index starts from 0 (January).

let dateComponents = new Date(2023, 11, 1); // December 1, 2023

Timestamp: Uses a numeric timestamp representing milliseconds since the UNIX epoch (January 1, 1970).

let timestamp = new Date(1670000000000);

Each of these methods offers flexibility in creating Date objects for various requirements in JavaScript programming.

Default Date and Time:

new Date();

This creates a Date object representing the current date and time.

From a Date String:

new Date(dateString);

Constructs a Date object from a specified date string (e.g., “2023-12-01”).

Specifying Date Components:

Year and Month:

new Date(year, month);

Year, Month, and Day:

new Date(year, month, day);

Year, Month, Day, and Hours:

new Date(year, month, day, hours);

Year, Month, Day, Hours, and Minutes:

new Date(year, month, day, hours, minutes);

Year, Month, Day, Hours, Minutes, and Seconds:

new Date(year, month, day, hours, minutes, seconds);

Complete Date with Milliseconds:

new Date(year, month, day, hours, minutes, seconds, ms);

From Milliseconds:

new Date(milliseconds);

Creates a Date object based on the number of milliseconds since January 1, 1970, UTC.

Author: user