Date Object
JavaScript uses the Date
object to handle date and time information.
Creating a Date Object
In JavaScript, you can create a new date object using new Date()
.
Creating a Date Object
const now = new Date();
console.log(now); // Outputs the current date and time
When a Date object is created, it contains the current date and time information. You can set or retrieve the date and time information in various ways as shown below.
Setting a Specific Date and Time
You can set a specific date and time when creating a Date object.
Setting a Specific Date and Time
const birthDay = new Date('1995-07-20');
console.log(birthDay);
Retrieving Year, Month, Day, Hour, Minute, Second
You can retrieve specific information from a Date object.
Retrieving Year, Month, Day, Hour, Minute, Second
const now = new Date();
// Year
const year = now.getFullYear();
// Month (starts at 0, so add 1)
const month = now.getMonth() + 1;
// Day
const date = now.getDate();
// Hour
const hours = now.getHours();
// Minute
const minutes = now.getMinutes();
// Second
const seconds = now.getSeconds();
Modifying Date and Time
It's also possible to modify the date or time information of a Date
object.
Modifying Date and Time
const birthDay = new Date('1995-07-20');
birthDay.setFullYear(2000); // Change year to 2000
birthDay.setMonth(0); // Change month to January (starts at 0)
birthDay.setDate(1); // Change day to 1st
console.log(birthDay);
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.