JavaScript Date and Time

Creating a Date Object

The Date object is used to work with dates and times. You can create a new Date object using the Date constructor.

Explanation of Code:

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

JavaScript




Getting Date and Time Values

This example demonstrates how to get various parts of the date and time using methods like getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds(), getMilliseconds(), and getDay().

JavaScript




Setting Date and Time Values

This example demonstrates how to set various parts of the date and time using methods like setFullYear(), setMonth(), setDate(), setHours(), setMinutes(), setSeconds(), and setMilliseconds().

JavaScript




Parsing Dates

You can create Date objects from date strings using the Date.parse() method or the Date constructor.

Explanation of Code:

The Date.parse() method parses a date string and returns the number of milliseconds since January 1, 1970, which can be used to create a Date object.

JavaScript




Formatting Dates

You can format dates using various methods like toDateString(), toTimeString(), toLocaleDateString(), toLocaleTimeString(), etc.

Explanation of Code:

This example demonstrates how to format dates using methods like toDateString(), toTimeString(), toLocaleDateString(), and toLocaleTimeString().

JavaScript




JavaScript Date and Time Example Code

Explanation of Code:

  • Creating a Date Object: Creates a Date object with the current date and time.
  • Getting Date Components: Retrieves various components of the date and time.
  • Setting Date Components: Updates various components of the date and time.
HTML




JavaScript Labs