Date in JavaScript
In this tutorial, we will learn how to work with dates in JavaScript using the Date object.
In JavaScript, the Date object is used to work with dates and times. It provides methods for creating, formatting, and manipulating dates.
Creating a Date Object
To create a new Date object, you can use the new Date() constructor. If you don't pass any arguments to the constructor, it will create a Date object representing the current date and time. Here is an example:
const currentDate = new Date();
console.log(currentDate); // Current date and timeYou can also create a Date object by passing a date string or a timestamp as an argument to the constructor. Here are some examples:
const date1 = new Date("2022-01-01");
console.log(date1); // Sat Jan 01 2022 00:00:00 GMT+0000 (Coordinated Universal Time)
const date2 = new Date(1640995200000); // Timestamp for 2022-01-01
console.log(date2); // Sat Jan 01 2022 00:00:00 GMT+0000 (Coordinated Universal Time)Getting Date and Time Components
The Date object provides methods to get various components of a date and time, such as the year, month, day, hour, minute, second, and millisecond. Here are some examples:
const date = new Date("2022-01-01");
console.log(date.getFullYear()); // 2022
console.log(date.getMonth()); // 0 (January is 0-based)
console.log(date.getDate()); // 1
console.log(date.getHours()); // 0
console.log(date.getMinutes()); // 0
console.log(date.getSeconds()); // 0Formatting Dates
You can format dates using the Date object's methods to get the date and time components and then concatenate them into a formatted string. Here is an example of formatting a date in the YYYY-MM-DD format:
const date = new Date("2022-01-01");
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate); // 2022-01-01Manipulating Dates
The Date object provides methods to manipulate dates by adding or subtracting time intervals. You can use these methods to perform operations like adding days to a date. Here is an example:
const date = new Date("2022-01-01");
date.setDate(date.getDate() + 7); // Add 7 days
console.log(date); // Sat Jan 08 2022 00:00:00 GMT+0000 (Coordinated Universal Time)Conclusion
- The
Dateobject in JavaScript is used to work with dates and times. - You can create a new
Dateobject using thenew Date()constructor. - The
Dateobject provides methods to get and set date and time components. - You can format dates by combining the date and time components into a formatted string.
- The
Dateobject provides methods to manipulate dates by adding or subtracting time intervals.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on