JavaScript Date Objects
1.Creating a Date Object:
Creating a Date Object:
Example
let currentDate = new Date();
2.Passing a timestamp:
This creates a Date object representing the date and time specified by the timestamp (milliseconds since January 1, 1970, 00:00:00 UTC).
Example
let specificDate = new Date(1625624200000);
3.Passing date components:
This creates a Date object representing June 10, 2022, at 12:30 PM.
Example
let specificDate = new Date(2022, 5, 10, 12, 30, 0);
Accessing Date Components:
You can access various components of a Date object, such as year, month, day, hour, minute, second, and millisecond:
Example
let date = new Date(); let year = date.getFullYear(); let month = date.getMonth(); // Note: Month is zero-based (0-11) let day = date.getDate(); let hour = date.getHours(); let minute = date.getMinutes(); let second = date.getSeconds(); let millisecond = date.getMilliseconds();
Formatting Dates:
JavaScript doesn't have built-in methods for formatting dates, but you can achieve it using various techniques or external libraries like Moment.js or date-fns.
Manipulating Dates:
You can manipulate dates using methods like setFullYear(), setMonth(), setDate(), setHours(), etc., to modify specific components of a Date object.
Working with Timestamps:
You can get the timestamp of a Date object using the getTime()
method, which returns the number of milliseconds since January 1, 1970.
Working with Timezones:
JavaScript Date objects operate in the local timezone of the user's browser. However, you can work with different timezones using libraries like Moment.js or by manually adjusting the time using methods like getTimezoneOffset().