JavaScript provides a built-in Date object that enables you to work with dates and times in your code. This object is used to represent a specific point in time and provides a range of methods that allow you to manipulate and format dates. In this blog, we will take a deep dive into the Date object, its properties, and methods, and explore how to use it in your code.
Creating a Date Object
T\use the Date()
constructor function. By default, this function creates a new Date object set to the current date and time. You can also create a Date object with a specific date and time by passing the relevant information as arguments to the constructor.
let now = new Date();
console.log(now); // logs the current date and time
let specificDate = new Date(2022, 10, 1);
console.log(specificDate); // logs "Tue Nov 01 2022 00:00:00 GMT+0500 (Pakistan Standard Time)"
Working with Date Properties
The Date object has several properties that allow you to retrieve information about a specific date and time. Some of the most commonly used properties include:
getDate()
: returns the day of the month (1-31)getDay()
: returns the day of the week (0-6)getFullYear()
: returns the year (4-digit)getHours()
: returns the hour (0-23)getMilliseconds()
: returns the milliseconds (0-999)getMinutes()
: returns the minutes (0-59)getMonth()
: returns the month (0-11)getSeconds()
: returns the seconds (0-59)getTime()
: returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
let date = new Date();
console.log(date.getDate()); // logs the current day of the month
console.log(date.getDay()); // logs the current day of the week
console.log(date.getFullYear()); // logs the current year
console.log(date.getHours()); // logs the current hour
console.log(date.getMilliseconds()); // logs the current milliseconds
console.log(date.getMinutes()); // logs the current minutes
console.log(date.getMonth()); // logs the current month
console.log(date.getSeconds()); // logs the current seconds
console.log(date.getTime()); // logs the number of milliseconds since January 1, 1970, 00:00:00 UTC
We will look into some date methods next