JavaScript’s Date object is a powerful tool for handling dates and times. It comes with built-in methods to create dates, retrieve date values, manipulate them, and format them. Here’s a deep dive into how you can use JavaScript’s Date functionality without any libraries.
1. Creating Dates
The JavaScript Date object can be created in multiple ways:
Example 1: Creating a Date with the Current Date and Time
const currentDate = new Date(); console.log(currentDate);
This will output the current date and time in the format of “Tue Oct 26 2024 10:00:00 GMT+0000 (UTC)”.
Example 2: Creating a Date with a Specific Date
You can pass date information in several formats.
Year, Month, Day, Hours, Minutes, Seconds, Milliseconds
const specificDate = new Date(2024, 9, 26, 10, 0, 0); // Oct is 9 because months are 0-indexed console.log(specificDate);
This outputs “Sat Oct 26 2024 10:00:00 GMT+0000 (UTC)”.
String Date Format
const stringDate = new Date("2024-10-26T10:00:00"); console.log(stringDate);
This outputs “Sat Oct 26 2024 10:00:00 GMT+0000 (UTC)”.
Date from Milliseconds Since Epoch
const epochDate = new Date(0); // January 1, 1970, 00:00:00 UTC console.log(epochDate);
This outputs “Thu Jan 01 1970 00:00:00 GMT+0000 (UTC)”.
2. Formatting Dates
JavaScript’s Date object lacks extensive formatting methods, so here’s how to manually format dates in a variety of common formats.
Example 1: Formatting as DD/MM/YY
const date = new Date(); const day = date.getDate().toString().padStart(2, "0"); const month = (date.getMonth() + 1).toString().padStart(2, "0"); // Months are zero-indexed const year = date.getFullYear().toString().slice(-2); const formattedDate = `${day}/${month}/${year}`; console.log(formattedDate);
This will output something like “26/10/24”.
Example 2: Formatting as MM/DD/YYYY
const monthDayYear = `${month}/${day}/${date.getFullYear()}`; console.log(monthDayYear);
This outputs “10/26/2024”.
Example 3: Formatting with YYYY-MM-DD (ISO Format)
The ISO format is a standard and is useful for many applications, especially for databases.
const isoDate = `${date.getFullYear()}-${month}-${day}`; console.log(isoDate);
This outputs “2024-10-26”.
3. Including Time
To add time in a format like HH:MM:SS, you can use the following:
const hours = date.getHours().toString().padStart(2, "0"); const minutes = date.getMinutes().toString().padStart(2, "0"); const seconds = date.getSeconds().toString().padStart(2, "0"); const dateTime = `${isoDate} ${hours}:${minutes}:${seconds}`; console.log(dateTime);
This outputs “2024-10-26 10:00:00”.
Example 1: Formatting Time in 12-Hour Format
let hour = date.getHours(); const ampm = hour >= 12 ? "PM" : "AM"; hour = hour % 12 || 12; // Convert 0 to 12 for 12 AM const time12Hour = `${hour}:${minutes} ${ampm}`; console.log(time12Hour);
This outputs something like “10:00 AM” or “12:00 PM”.
4. Extracting and Manipulating Date Components
Example 1: Getting Day, Month, and Year Separately
console.log("Day:", date.getDate()); // Outputs day (1-31) console.log("Month:", date.getMonth() + 1); // Outputs month (1-12) console.log("Year:", date.getFullYear()); // Outputs full year (e.g., 2024)
Example 2: Adding and Subtracting Days
Adding Days
const addDays = (date, days) => { const newDate = new Date(date); newDate.setDate(newDate.getDate() + days); return newDate; }; const newDatePlus5 = addDays(date, 5); console.log(newDatePlus5);
Subtracting Days
const newDateMinus5 = addDays(date, -5); console.log(newDateMinus5);
5. Comparing Dates
JavaScript’s Date objects can be compared directly because they represent a timestamp:
const date1 = new Date("2024-10-26"); const date2 = new Date("2024-11-01"); console.log(date1 > date2); // false console.log(date1 < date2); // true console.log(date1.getTime() === date2.getTime()); // false
6. Handling Time Zones
JavaScript Date is typically in local time but can be displayed in UTC or other time zones:
Convert to UTC Time
const utcDate = date.toUTCString(); console.log(utcDate); // "Sat, 26 Oct 2024 10:00:00 GMT"
Convert to Locale String
const localeDate = date.toLocaleDateString("en-GB"); // e.g., "26/10/2024" for UK format console.log(localeDate);
Locale Time String
const localeTime = date.toLocaleTimeString("en-US"); // e.g., "10:00:00 AM" for US format console.log(localeTime);
7. Full Example: Dynamic Date Formatting Function
Here’s a reusable function to format dates in different ways:
function formatDate(date, format) { const day = date.getDate().toString().padStart(2, "0"); const month = (date.getMonth() + 1).toString().padStart(2, "0"); const year = date.getFullYear(); const hours = date.getHours().toString().padStart(2, "0"); const minutes = date.getMinutes().toString().padStart(2, "0"); const seconds = date.getSeconds().toString().padStart(2, "0"); return format .replace("DD", day) .replace("MM", month) .replace("YYYY", year) .replace("YY", year.toString().slice(-2)) .replace("HH", hours) .replace("mm", minutes) .replace("ss", seconds); } const myDate = new Date(); console.log(formatDate(myDate, "DD/MM/YY")); // "26/10/24" console.log(formatDate(myDate, "MM-DD-YYYY")); // "10-26-2024" console.log(formatDate(myDate, "YYYY-MM-DD HH:mm")); // "2024-10-26 10:00"
Summary
The JavaScript Date object, though limited in native formatting capabilities, can be customized to work with a variety of date and time formats, offering a flexible approach to manipulating dates without relying on external libraries. With the above examples, you should have a solid foundation to use and format dates in JavaScript.