Change date in new date js
In JavaScript, you can use the Date
object to change the date. Here are a few ways to do it:
Method 1: Using the setDate()
method
const date = new Date();
date.setDate(15); // set the day of the month to 15
console.log(date); // Output: Fri Jan 15 2022 00:00:00 GMT+0000 (Coordinated Universal Time)
Method 2: Using the setFullYear()
method
const date = new Date();
date.setFullYear(2022, 0, 15); // set the year to 2022, month to January, and day to 15
console.log(date); // Output: Fri Jan 15 2022 00:00:00 GMT+0000 (Coordinated Universal Time)
Method 3: Using the setUTCDate()
method
const date = new Date();
date.setUTCDate(15); // set the day of the month to 15 (UTC)
console.log(date); // Output: Fri Jan 15 2022 00:00:00 UTC
Method 4: Using the setUTCFullYear()
method
const date = new Date();
date.setUTCFullYear(2022, 0, 15); // set the year to 2022, month to January, and day to 15 (UTC)
console.log(date); // Output: Fri Jan 15 2022 00:00:00 UTC
Note that the setDate()
and setUTCDate()
methods only change the day of the month, while the setFullYear()
and setUTCFullYear()
methods change the year, month, and day.
Also, keep in mind that these methods modify the original Date
object. If you want to create a new Date
object with the modified date, you can use the new Date()
constructor again:
const originalDate = new Date();
const modifiedDate = new Date(originalDate.getFullYear(), originalDate.getMonth(), 15);
console.log(modifiedDate); // Output: Fri Jan 15 2022 00:00:00 GMT+0000 (Coordinated Universal Time)