In Javascript, The Date object is used to work with dates and times. We can create a current date and time and a specific date and time using date objects.
Date object helps us to implement time-sensitive tasks like recurring tasks, cron jobs, scheduling tasks, calculating date and time differences, or specifying the current date and time.
It provides methods for creating, manipulating, and formatting dates.
Here are the examples of how we can use Date Module in Javascript:
We can create a Date object in several ways.
let currentDate = new Date();
let specificDate = new Date("2023-03-03T23:30:00");
let dateComponents = new Date(2023, 3, 3, 23, 30, 0); // Months are zero-based (0-11)
We can retrieve various info of a Date object using its methods.
let date = new Date(); console.log(date.getFullYear()); // 2023 console.log(date.getMonth()); // 3 (Months are zero-based) console.log(date.getDate()); // 3 console.log(date.getDay()); // 5 (Day of the week: 0-Sunday, 1-Monday, ..., 6-Saturday)
console.log(date.getHours()); // Current hour console.log(date.getMinutes()); // Current minute console.log(date.getSeconds()); // Current second
JavaScript doesn't have built-in formatting methods for dates, but we can create a custom function or use external libraries like Intl.DateTimeFormat or third-party libraries like moment.js for more advanced formatting.
let date = new Date(); // Example using Intl.DateTimeFormat let formattedDate = new Intl.DateTimeFormat('en-US').format(date); console.log(formattedDate); // "3/3/2023" // Example using toLocaleString let formattedDate2 = date.toLocaleString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); console.log(formattedDate2); // "Friday, March 3, 2023"
We can perform arithmetic operations on Date objects to calculate time differences or add/subtract time.
let currentDate = new Date(); let futureDate = new Date(currentDate.getTime() + 5 * 24 * 60 * 60 * 1000); // Adding 5 days
Timestamps represent the number of milliseconds since January 1, 1970
let timestamp = Date.now(); console.log(timestamp);