#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 44 of 50medium

How to work with Dates in JavaScript?

Understanding Date object and manipulation.

What You'll Learn

  • Creating dates
  • Getting/setting date parts
  • Formatting dates

Creating Dates

code.jsJavaScript
// Current date/time
const now = new Date();

// From string
const date1 = new Date('2024-01-15');
const date2 = new Date('January 15, 2024');

// From values (month is 0-indexed!)
const date3 = new Date(2024, 0, 15); // Jan 15, 2024
const date4 = new Date(2024, 0, 15, 10, 30, 0);

// From timestamp
const date5 = new Date(1705276800000);

Getting Date Parts

code.jsJavaScript
const date = new Date('2024-01-15T10:30:00');

date.getFullYear();   // 2024
date.getMonth();      // 0 (January)
date.getDate();       // 15
date.getDay();        // 1 (Monday)
date.getHours();      // 10
date.getMinutes();    // 30
date.getTime();       // Timestamp

Setting Date Parts

code.jsJavaScript
const date = new Date();

date.setFullYear(2025);
date.setMonth(5);     // June
date.setDate(20);
date.setHours(14);

Date Calculations

code.jsJavaScript
// Add days
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

// Difference in days
const date1 = new Date('2024-01-01');
const date2 = new Date('2024-01-15');
const diffMs = date2 - date1;
const diffDays = diffMs / (1000 * 60 * 60 * 24); // 14

Formatting

code.jsJavaScript
const date = new Date();

// Built-in methods
date.toISOString();     // '2024-01-15T10:30:00.000Z'
date.toLocaleDateString(); // '1/15/2024'
date.toLocaleTimeString(); // '10:30:00 AM'

// Intl.DateTimeFormat
new Intl.DateTimeFormat('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric'
}).format(date); // 'January 15, 2024'