JavaScript gives you powerful tools to manipulate date and time — from fetching the current timestamp to comparing future dates, and even calculating years since 1970.
In this guide, we’ll explore both get and set date methods in JavaScript, including how to handle local vs. UTC time.
🔹 Getting the Current Date
const now = new Date();
console.log(now);
This returns the current local date and time.
Common get
Methods
Method | What It Returns |
---|---|
getFullYear() |
Full year (e.g. 2025) |
getMonth() |
Month (0-11, where Jan = 0) |
getDate() |
Day of month (1-31) |
getDay() |
Weekday (0-6, where Sun = 0) |
getHours() |
Hour (0-23) |
getMinutes() |
Minutes (0-59) |
getSeconds() |
Seconds (0-59) |
getMilliseconds() |
Milliseconds (0-999) |
getTime() |
Time since Jan 1, 1970 in milliseconds |
Example:
const today = new Date();
console.log("Year:", today.getFullYear());
console.log("Month:", today.getMonth()); // Jan = 0
console.log("Day:", today.getDate());
🔹 Setting Dates in JavaScript
You can also set specific parts of a date using methods like setFullYear()
, setDate()
, and setHours()
.
Common set
Methods
Method | Description |
---|---|
setFullYear() |
Set year, optionally month and day |
setMonth() |
Set month (0–11) |
setDate() |
Set day of month |
setHours() |
Set hour (0–23) |
setMinutes() |
Set minutes (0–59) |
setSeconds() |
Set seconds (0–59) |
setTime() |
Set milliseconds since 1970 |
Example:
const d = new Date("January 01, 2025");
d.setFullYear(2020, 11, 3); // Year: 2020, Month: December, Day: 3
console.log(d);
🌍 UTC vs Local Time
- Use
getUTCFullYear()
,getUTCMonth()
, etc. to fetch time in UTC format. - Local time is system-based; UTC is universal.
const d = new Date();
console.log("Local:", d.getHours());
console.log("UTC:", d.getUTCHours());
⏱️ Date.now() and Time Calculations
Want to calculate how many years have passed since 1970?
const yearMs = 1000 * 60 * 60 * 24 * 365;
const yearsSince1970 = Math.round(Date.now() / yearMs);
console.log(yearsSince1970);
📘 Recommended JavaScript Books (Affiliate)
Level up your learning with these highly rated books:
1. Mastering HTML, CSS & JavaScript Web Publishing
2. Learning JavaScript Design Patterns by Addy Osmani
3. JavaScript: The Definitive Guide by David Flanagan
🧠 Exercise Time
What will the following return?
const fruits = ['Apple', 'Orange', 'Banana'];
fruits.reverse();
🤔 Answer in the comments!
Top comments (0)