JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Set Date Methods

8 April 2025 | Category:

JavaScript provides set methods to change the values of a Date object — like the year, month, day, hour, etc.

These methods allow you to update date and time parts after a Date object is created.


✅ Create a Date Object

Before using set methods, create a Date object:

const date = new Date(); // current date and time

📋 List of Set Methods

MethodDescription
setFullYear(year)Sets the full year (4 digits)
setMonth(month)Sets the month (0–11)
setDate(day)Sets the day of the month (1–31)
setHours(hour)Sets the hour (0–23)
setMinutes(min)Sets the minutes (0–59)
setSeconds(sec)Sets the seconds (0–59)
setMilliseconds(ms)Sets the milliseconds (0–999)
setTime(ms)Sets the time (milliseconds since 1970)

🔍 Examples

const date = new Date();

date.setFullYear(2030);
date.setMonth(11);        // December (0 = Jan)
date.setDate(25);         // 25th
date.setHours(10);        // 10 AM
date.setMinutes(30);      // 30 minutes
date.setSeconds(15);      // 15 seconds

console.log(date); // Outputs: Wed Dec 25 2030 10:30:15 ...

✅ setTime()

Set time directly using milliseconds since Jan 1, 1970:

const date = new Date();
date.setTime(1744100000000);
console.log(date); // New date based on the timestamp

🔄 Chaining Setters

You can use multiple set methods together:

const d = new Date();
d.setFullYear(2028);
d.setMonth(0);
d.setDate(1);
console.log(d); // Sat Jan 01 2028

🧠 Notes

  • setMonth(0) means January, setMonth(11) means December.
  • If you pass a value out of range, JavaScript auto-adjusts: const d = new Date(); d.setDate(32); // Rolls over to the next month console.log(d); // Example: Thu May 02 2025

🧪 Real-World Example: Add 7 Days to Today

const today = new Date();
today.setDate(today.getDate() + 7);
console.log(today); // Date after 7 days

📌 Summary

Use set methods to:

  • Change parts of a date (year, month, time, etc.)
  • Calculate future or past dates
  • Update timestamps manually