Working with Date in nay languages is painful so let reduce this pain.
JavaScript offers us a date handling functionality through a painfull built-in object: Date.
Tip: you might want to use a library when working with dates. Moment.js and date-fns are two of the most popular ones.
The Date Object
Despite being named Date, it also handles time.
We initialize a Date object by using
new Date()
//output: 2024-09-08T06:53:21.941Z
By default, this returns the current date and time based on the user’s system clock.
You can create a Date object with a specific date by passing a string or individual year, month, day and time.
// Creating date by input
const specificDate = new Date("2024-09-08");
console.log("Specific Date: ", specificDate)
// Using year, month, and day (Month is zero-indexed, so 8 is September)
const anotherDate = new Date(2023, 8, 8);
console.log(anotherDate);
2. Retrieving and Setting Date Components
The Date object provides several methods to get individual components such as the year, month, day, ours, minutes, and seconds.
Getting Date Components
const today = new Date();
console.log(today.getFullYear()); // Current year
console.log(today.getMonth()); // Current month (0-11, 0 = January)
console.log(today.getDate()); // Current day of the month
console.log(today.getDay()); // Day of the week (0 = Sunday)
console.log(today.getHours()); // Hours (0-23)
console.log(today.getMinutes()); // Minutes (0-59)
console.log(today.getSeconds()); // Seconds (0-59)
//output
/*
Current year: 2024
Current month (0-11, 0 = January): 8
Current day of the month: 8
Day of the week (0 = Sunday): 0
Hours (0-23): 13
Minutes (0-59): 16
Seconds (0-59): 40
*/
Setting Date Components
You can modify the Date object’s components by using the setter methods.
let futureDate = new Date();
futureDate.setFullYear(2025);
futureDate.setMonth(11); // December (0-indexed)
futureDate.setDate(25); // Christmas
console.log("Setting custom date:", futureDate);
/*
Setting custom date: 2025-12-25T07:49:20.373Z
*/
03. Formatting Dates
JavaScript Date objects can be displayed in a variety of formats. By default, when you log a Date object, it is displayed in the ISO format. However, there are methods to control how dates are presented.
toLocaleDateString()
You can format dates according to locale preferences:
//Date Formatting
const date = new Date();
console.log("MM/DD/YYYY: ",date.toLocaleDateString('en-US')); // MM/DD/YYYY
console.log("DD/MM/YYYY: ", date.toLocaleDateString('en-GB')); // DD/MM/YYYY
/*
Output:
MM/DD/YYYY: 9/8/2024
DD/MM/YYYY: 08/09/2024
*/
toISOString()
This method is used to get a date in the ISO 8601 format:
const isoDate = new Date().toISOString();
console.log(isoDate); // "2023-09-08T14:34:00.000Z"
Date Arithmetic
Date arithmetic involves adding or subtracting time to or from a date, comparing dates, and finding the difference between dates.
Adding Time
To add days, hours, or other components to a date, you can use the setter methods in combination with getTime():
// Date arithmetic
const dateEx1 = new Date();
const tomorrow = new Date(dateEx1);
tomorrow.setDate(dateEx1.getDate() + 1); // Adds one day
console.log("Date arithmetic Example: ",tomorrow);
Difference Between Dates
To calculate the difference between two dates, subtract them, and you will get the result in milliseconds:
// Comparing date
const startDate = new Date("2023-09-01");
const endDate = new Date("2023-09-08");
const differenceInTime = endDate - startDate; // Difference in milliseconds
const differenceInDays = differenceInTime / (1000 * 60 * 60 * 24); // Convert to days
console.log("Comparing two date:",differenceInDays); // 7 days
Working with Time Zones
Time zones can be tricky when working wit date especially in global application. Javascript dates are usually based on the local time zone of the user’s device.
Getting Time Zone Information
You can get the UTC (Universal Time Coordinated) values or convert a date to UTC:
const now = new Date();
console.log(now.getUTCDate()); // UTC date
console.log(now.getUTCHours()); // UTC hours
Handling Time Zone Differences
When dealing with users from different time zones, it’s often useful to store dates in UTC and then convert them to the user’s local time zone when displaying them.
const utcDate = new Date(Date.UTC(2023, 8, 8, 12, 0, 0)); // Date in UTC
console.log(utcDate.toLocaleString()); // Convert to local time zone
Comparing Dates
In JavaScript, comparing dates can be done using the standard comparison operators. Since dates are represented as timestamps, you can directly compare them:
//Compare dates
const date1 = new Date("2023-09-08");
const date2 = new Date("2023-09-10");
if (date1 > date2) {
console.log("Date1 is later than Date2");
} else {
console.log("Date1 is earlier than Date2");
}
7. Common Mistakes When Working with Dates
1. Zero-indexed Months
JavaScript months are zero-indexed, meaning January is 0 and December is 11. Forgetting this can lead to off-by-one errors when dealing with months.
const wrongDate = new Date(2023, 9, 1); // October 1st, not September
2. Date Mutability
Date objects are mutable, which means when you modify a date, it changes the original object. Be careful when passing date objects around and making changes, as you might unintentionally alter them.
Links to read more about date in JS https://flaviocopes.com/javascript-dates/ , https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date