DEV Community

Cover image for JavaScript Tutorial Series: Date Object
The daily developer
The daily developer

Posted on • Edited on

JavaScript Tutorial Series: Date Object

A built-in Date object in JavaScript makes working with dates simple. We will discuss how to use dates in this article.

Working with dates

A new Date object can be easily created. A new instance of the Date object can be made using this syntax:

let currentDate = new Date();
Enter fullscreen mode Exit fullscreen mode

By doing this, a new Date object will be created with the current date and time.

Date methods and properties

The Date object has multiple built-in methods and properties. We're going to discuss the most commonly used.

Once you have a Date object, you can extract a variety of data from it. For example, you can find the current year, month, day, and time.

let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentMonth = currentDate.getMonth();
let currentDay = currentDate.getDate();
let currentTime = currentDate.getTime();

console.log(currentYear); //2023
console.log(currentMonth); //1
console.log(currentDay); //23
console.log(currentTime); //1677176048519
Enter fullscreen mode Exit fullscreen mode

Keep in mind getMonth() returns zero-based index and getTime() returns the amount of milliseconds that have passed since the epoch, which is recognized as the beginning of January 1, 1970, UTC at midnight.

setFullYear(), setMonth(), setDate(), and setTime() methods allow you to set a specific date and time.

let currentDate = new Date();
currentDate.setFullYear(2021);
currentDate.setMonth(9); // september (zero-based)
currentDate.setDate(15);
currentDate.setTime(0); // Sets the time to midnight
Enter fullscreen mode Exit fullscreen mode

Along with getting and setting specific date and time components, you also have the choice of performing operations on dates. For instance, you can add or subtract a certain number of days, hours, or minutes from a date by using the setDate(), setHours(), and setMinutes() methods.

let currentDate= new Date();
currentDate.setDate(currentDate.getDate() + 3); 
// Adds 3 days
currentDate.setHours(currentDate.getHours() - 5); 
// Subtracts 5 hours
currentDate.setMinutes(currentDate.getMinutes() + 10); 
// Adds 10 minutes
Enter fullscreen mode Exit fullscreen mode

Last but not least, you can format dates for display by using the toLocaleDateString() and toLocaleTimeString() methods. The user's locale settings will be used by these methods to format the date and time.

Do not forget to try these snippets and output the result on your own to get the hang of using the date object.

Top comments (0)