- Home
- /
- Date
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- Date
Dates in JavaScript
In JavaScript, the Date
object is your go-to tool for handling anything related to time and dates. Whether you’re building a calendar, logging timestamps, or calculating the difference between two dates, this built-in object has what you need.
Getting the Current Date and Time
To create a date object with the current date and time, just call new Date()
without any arguments:
let now = new Date();
console.log(now);
Output
Thu Jul 04 2025 10:32:00 GMT+0500 (Pakistan Standard Time)
The Date
object automatically picks up your system’s local time zone unless otherwise specified.
Setting a Specific Date
You can also create a date for a specific day and time by passing values like year, month (0-based), day, hour, and so on.
let birthday = new Date(2000, 11, 25); // December 25, 2000
console.log(birthday);
Want more control? You can update parts of an existing date using setter methods:
let event = new Date();
event.setFullYear(2026);
event.setMonth(0); // January
event.setDate(15);
console.log(event);
Extracting Information from a Date
Once you have a Date
object, you can extract any part of it — like the day, month, or year.
let date = new Date();
console.log(date.getFullYear()); // 2025
console.log(date.getMonth()); // 6 (July, because months are 0-indexed)
console.log(date.getDate()); // 4
console.log(date.getHours()); // e.g., 10
Formatting Dates with toLocaleString()
The raw date format from console.log(date)
isn’t always user-friendly. JavaScript offers a nice method for formatting:
let formatted = new Date().toLocaleString();
console.log(formatted); // e.g., 7/4/2025, 10:32:00 AM
You can even specify locale and time zone:
console.log(new Date().toLocaleString('en-GB')); // British format
console.log(new Date().toLocaleString('en-US', { timeZone: 'UTC' }));
Real-Life Example
Let’s say you’re building a countdown app and want to show how many days are left until New Year’s:
let today = new Date();
let nextYear = new Date(today.getFullYear() + 1, 0, 1);
let msLeft = nextYear - today;
let daysLeft = Math.floor(msLeft / (1000 * 60 * 60 * 24));
console.log(`Only ${daysLeft} days left until New Year!`);
Conclusion
The Date
object is a powerful built-in feature that helps you create, format, and manipulate time in JavaScript. Whether you’re just displaying the current time or handling time zones, Date
gives you the tools to do it easily.