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
Various Uses of the Date Object
-
Setting a specific date and time: You can set a specific date and time when creating a
Date
object.Setting a specific date and timeconst birthDay = new Date('1995-07-20');
console.log(birthDay);
-
Getting year, month, day, hour, minute, and second: You can retrieve specific information from the
Date
object.Getting year, month, day, hour, minute, and secondconst now = new Date();
const year = now.getFullYear(); // Year
const month = now.getMonth() + 1; // Month (starts from 0 so add 1)
const date = now.getDate(); // Day
const hours = now.getHours(); // Hour
const minutes = now.getMinutes(); // Minute
const seconds = now.getSeconds(); // Second
-
Changing the date and time: You can also change the date or time information of the
Date
object.Changing the date and timeconst birthDay = new Date('1995-07-20');
birthDay.setFullYear(2000); // Change year to 2000
birthDay.setMonth(0); // Change month to January (starts from 0)
birthDay.setDate(1); // Change day to 1
console.log(birthDay);
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.