π§ JavaScript Date and Time β The Easy Way
Working with dates and times is super important in JavaScript β whether you're showing the current time, scheduling something, or formatting a birthday. JavaScript has a built-in Date
object to help you out.
π Creating a Date
let now = new Date();
console.log(now); // current date and time
let specificDate = new Date("2023-10-01");
console.log(specificDate); // Sun Oct 01 2023
π΅οΈββοΈ Getting Date Parts
Use these methods to grab specific parts of the date:
let today = new Date();
console.log(today.getFullYear()); // 2025
console.log(today.getMonth()); // 0-11 (0 = Jan)
console.log(today.getDate()); // 1-31
console.log(today.getDay()); // 0-6 (0 = Sunday)
console.log(today.getHours()); // 0-23
console.log(today.getMinutes()); // 0-59
console.log(today.getSeconds()); // 0-59
π οΈ Setting Date Values
let birthday = new Date();
birthday.setFullYear(1995);
birthday.setMonth(11); // December
birthday.setDate(25);
console.log(birthday);
π¦ Formatting a Date
Turn it into something readable for your users:
let date = new Date();
console.log(date.toDateString()); // "Sat Mar 29 2025"
console.log(date.toLocaleDateString()); // formatted by locale
console.log(date.toLocaleTimeString()); // only time
β±οΈ Timestamps
let now = new Date();
console.log(now.getTime()); // milliseconds since Jan 1, 1970
let later = new Date();
console.log(later - now); // difference in milliseconds
β TL;DR β Date Method Cheatsheet
- new Date() β create a new date object
- getFullYear() β get the year
- getMonth() β get month (0β11)
- getDate() β get day of month
- getDay() β get day of week
- setFullYear(), setMonth(), etc. β set date parts
- toDateString(), toLocaleDateString() β format dates
- getTime() β get timestamp (ms)
π‘ Pro Tip: Always double-check months β JavaScript counts them from 0 (January) to 11 (December)!