Hello friends! Let's delve into the fascinating topic of date and time manipulation in JavaScript together. In the realm of programming, working with date and time is one of those tasks that frequently goes unnoticed. Whether you're building a simple application or crafting larger projects like calendars, timers, or something akin to this, you must work with dates invariably.
JavaScript offers a rich set of methods for modifying and adjusting dates. Suppose you want to change the date of a particular factor to a different date. Or maybe you'd like to replace the start time of a specific event. Well, JavaScript provides multiple user-friendly ways in this area at your disposal.
First of all, I’ll tell you that the methods for adjusting JavaScript dates are quite straightforward. You can use these methods to set the year, month, day, hour, minute, and even second to whatever you want. Each time you need to adjust, you can control it in a very interesting way.
Let's take a look at some of these well-known methods. For instance, we have `setFullYear`, which allows you to set the year of the date. Suppose you have a date and you only want to change its year; with this ability, you can easily do that.
Example code for setting the date:
let date = new Date();
// setting the year
date.setFullYear(2025);
// setting the month (months start from 0, so 0 = January)
date.setMonth(11);
// setting the day of the month
date.setDate(25);
// setting the hour
date.setHours(15);
// setting the minute
date.setMinutes(45);
// setting the second
date.setSeconds(30);
console.log(date);
Line-by-line explanation of the code:
let date = new Date();
This line creates a new instance of the Date object. Now we can work with it.
date.setFullYear(2025);
This line sets the year to 2025.
date.setMonth(11);
This line sets the month to December since months in JavaScript start from 0, hence 11 is December.
date.setDate(25);
This line sets the day of the month to 25.
date.setHours(15);
This line sets the hour to 15, which is equivalent to 3 PM.
date.setMinutes(45);
This line sets the minute to 45.
date.setSeconds(30);
This line sets the seconds to 30.
console.log(date);
This line outputs the date in its full format to the console so you can see the result.