JavaScript provides robust functionality to handle date and time through the Date object and various methods associated with it. This guide will cover the creation, manipulation, and formatting of dates and times in JavaScript, including practical examples.
1. Creating Dates
Using the Date Constructor
The Date object can be instantiated in several ways:
Current Date and Time
let now = new Date();
console.log(now);
Specific Date and Time
let specificDate = new Date(2024, 4, 31, 10, 30, 0, 0);
console.log(specificDate);
Note: Months are zero-indexed (January is 0, December is 11).
Date String
let dateString = new Date('May 31, 2024 10:30:00');
console.log(dateString);
Milliseconds Since Epoch
let epochTime = new Date(1656500300000);
console.log(epochTime);
Date Components
let dateComponents = new Date(Date.UTC(2024, 4, 31, 10, 30, 0));
console.log(dateComponents);
2. Getting Date and Time Components
Getting the Full Date and Time
- getFullYear(): Returns the year.
- getMonth(): Returns the month (0-11).
- getDate(): Returns the day of the month (1-31).
- getDay(): Returns the day of the week (0-6).
- getHours(): Returns the hour (0-23).
- getMinutes(): Returns the minutes (0-59).
- getSeconds(): Returns the seconds (0-59).
- getMilliseconds(): Returns the milliseconds (0-999).
- getTime(): Returns the number of milliseconds since January 1, 1970.
Example:
let date = new Date();
console.log(date.getFullYear()); // 2024
console.log(date.getMonth()); // 4 (May)
console.log(date.getDate()); // 31
console.log(date.getDay()); // 5 (Friday)
console.log(date.getHours()); // 10
console.log(date.getMinutes()); // 30
console.log(date.getSeconds()); // 0
console.log(date.getMilliseconds()); // 0
console.log(date.getTime()); // 1656500300000 (example)
Getting UTC Date and Time Components
- getUTCFullYear()
- getUTCMonth()
- getUTCDate()
- getUTCDay()
- getUTCHours()
- getUTCMinutes()
- getUTCSeconds()
- getUTCMilliseconds()
Example:
console.log(date.getUTCFullYear()); // 2024
console.log(date.getUTCMonth()); // 4 (May)
console.log(date.getUTCDate()); // 31
console.log(date.getUTCHours()); // 10
3. Setting Date and Time Components
Setting the Full Date and Time
- setFullYear(year, [month], [day])
- setMonth(month, [day])
- setDate(day)
- setHours(hours, [minutes], [seconds], [milliseconds])
- setMinutes(minutes, [seconds], [milliseconds])
- setSeconds(seconds, [milliseconds])
- setMilliseconds(milliseconds)
- setTime(milliseconds)
Example:
let newDate = new Date();
newDate.setFullYear(2025);
newDate.setMonth(11); // December
newDate.setDate(25);
newDate.setHours(12, 0, 0, 0); // 12:00:00.000
console.log(newDate);
Setting UTC Date and Time Components
- setUTCFullYear(year, [month], [day])
- setUTCMonth(month, [day])
- setUTCDate(day)
- setUTCHours(hours, [minutes], [seconds], [milliseconds])
- setUTCMinutes(minutes, [seconds], [milliseconds])
- setUTCSeconds(seconds, [milliseconds])
- setUTCMilliseconds(milliseconds)
Example:
newDate.setUTCFullYear(2025);
newDate.setUTCMonth(11); // December
newDate.setUTCDate(25);
newDate.setUTCHours(12, 0, 0, 0); // 12:00:00.000 UTC
console.log(newDate);
4. Parsing Dates
Using Date.parse()
This method parses a date string and returns the number of milliseconds since January 1, 1970:
let millis = Date.parse('May 31, 2024 10:30:00');
console.log(millis); // 1704063000000
Using Date.UTC()
This method returns the number of milliseconds between a specified date and January 1, 1970:
let utcMillis = Date.UTC(2024, 4, 31, 10, 30, 0);
console.log(utcMillis); // 1704063000000
5. Formatting Dates
Converting to ISO String
toISOString(): Converts the date to a string in ISO 8601 format:
console.log(date.toISOString()); // 2024-05-31T10:30:00.000Z
Converting to Date String
toDateString(): Converts the date to a readable string:
console.log(date.toDateString()); // Fri May 31 2024
Converting to Time String
toTimeString(): Converts the time to a readable string:
console.log(date.toTimeString()); // 10:30:00 GMT+0000 (Coordinated Universal Time)
Converting to Locale String
toLocaleDateString(): Converts the date to a string based on the locale:
console.log(date.toLocaleDateString()); // 5/31/2024
toLocaleTimeString(): Converts the time to a string based on the locale:
console.log(date.toLocaleTimeString()); // 10:30:00 AM
toLocaleString(): Converts the date and time to a string based on the locale:
console.log(date.toLocaleString()); // 5/31/2024, 10:30:00 AM
Custom Formatting
For more complex formatting, libraries like moment.js or date-fns can be used. However, with the introduction of the Intl.DateTimeFormat object, custom formatting can be achieved natively:
Example:
let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(new Intl.DateTimeFormat('en-US', options).format(date)); // Friday, May 31, 2024
6. Comparing Dates
Comparing Two Dates
- date1 > date2
- date1 < date2
- date1 >= date2
- date1 <= date2
- date1.getTime() === date2.getTime()
Example:
let date1 = new Date('2024-05-31');
let date2 = new Date('2025-05-31');
console.log(date1 < date2); // true
console.log(date1.getTime() === date2.getTime()); // false
Calculating Differences
To find the difference between two dates, subtract their timestamps:
let diffInMillis = date2 - date1;
let diffInDays = diffInMillis / (1000 * 60 * 60 * 24); // Milliseconds to days
console.log(diffInDays); // 366 (leap year)
Conclusion
The Date object in JavaScript provides comprehensive functionality for handling dates and times. By understanding and leveraging these methods, developers can effectively manage date and time operations in their applications. For more advanced use cases, consider integrating additional libraries like moment.js or date-fns, which offer even more powerful date manipulation and formatting features.