Javascript new date

The Date object in JavaScript!

The Date object is a built-in object that represents a date and time. You can create a new Date object using the new Date() constructor, which returns a Date object with the current date and time.

Here are some ways to create a new Date object:

  1. Default constructor: new Date() This creates a Date object with the current date and time.

    const now = new Date();
    console.log(now); // Output: current date and time
  2. Constructor with arguments: new Date(year, month, day, hours, minutes, seconds, milliseconds) This creates a Date object with the specified date and time.

    const date = new Date(2022, 5, 12, 14, 30, 0, 0);
    console.log(date); // Output: June 12, 2022 02:30:00.000

    Note that the month argument is 0-based, meaning January is 0 and December is 11.

  3. Constructor with a string: new Date(string) This creates a Date object from a string in the format YYYY-MM-DDTHH:MM:SS.SSSZ.

    const date = new Date('2022-06-12T14:30:00.000Z');
    console.log(date); // Output: June 12, 2022 02:30:00.000
  4. Constructor with a timestamp: new Date(timestamp) This creates a Date object from a timestamp in milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC).

    const timestamp = 1652336400000;
    const date = new Date(timestamp);
    console.log(date); // Output: June 12, 2022 02:30:00.000

    Once you have a Date object, you can access various properties and methods to work with the date and time. Some common properties and methods include: