JavaScript's Date object provides various methods to format and manipulate date and time. Here are some examples:
Creating a Date object:
let currentDate = new Date();
Getting specific parts of the date or time:
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1; // Months are zero-based, so add 1
let day = currentDate.getDate();
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();
Formatting date and time:
let formattedDate = currentDate.toLocaleDateString();
let formattedTime = currentDate.toLocaleTimeString();
let formattedDateTime = currentDate.toLocaleString();
Manipulating date and time:
// Add or subtract days
currentDate.setDate(currentDate.getDate() + 7);
// Add or subtract hours
currentDate.setHours(currentDate.getHours() - 3);
// Add or subtract minutes
currentDate.setMinutes(currentDate.getMinutes() + 15);
// Add or subtract seconds
currentDate.setSeconds(currentDate.getSeconds() - 30);
Comparing dates:
let date1 = new Date('2022-01-01');
let date2 = new Date('2022-01-05');
if (date1 < date2) {
console.log('date1 is before date2');
} else if (date1 > date2) {
console.log('date1 is after date2');
} else {
console.log('date1 and date2 are equal');
}
Note: The above examples demonstrate only a few common operations. JavaScript's Date object provides many more methods for manipulating and formatting dates and times.