Table of contents

  1. Introduction to Date and Time in JavaScript
    • Overview of the Date Object and its capabilities.
  2. Creating a Date Object
    • Example 1: Creating a Date Object
    • Example 2: Creating a Date Object with Specific Date and Time
    • Example 3: Creating a Date Object from a String Representation
  3. Getting and Setting Date Components
    • Example 1: Getting Current Date Components
    • Example 2: Setting Date Components
    • Example 3: Getting Day of the Week
    • Example 4: Getting Hours, Minutes, and Seconds
    • Example 5: Getting and Setting UTC Date Components
  4. Formatting Dates
    • Example 1: Formatting Date to ISO 8601 Format
    • Example 2: Custom Date Formatting Function
    • Example 3: Formatting Date for Display
    • Example 4: Formatting Date Components Separately
    • Example 5: Formatting Date with Time Zone Offset
    • Example 6: Formatting Date with Locale Settings
  5. Working with Time Zones
    • Example 1: Converting Date to UTC
    • Example 2: Converting UTC Date to Local Time
    • Example 3: Displaying UTC Date in Local Time Zone
    • Example 4: Getting Time Zone Offset
    • Example 5: Displaying Date and Time in Different Time Zones
    • Example 6: Handling Daylight Saving Time Changes
  6. Manipulating Dates
    • Example 1: Adding Days to a Date
    • Example 2: Subtracting Days from a Date
    • Example 3: Adding Months to a Date
    • Example 4: Comparing Two Dates
    • Example 5: Calculating Age from Birth Date
    • Example 6: Finding Days Between Two Dates
  7. Best Practices and Considerations
    • Using UTC Methods for Time Zone-agnostic Operations
    • Properly Handling Date Formatting Based on Locale
    • Ensuring Consistent Date Manipulations Across Time Zones

1. Introduction to Date and Time in JavaScript

  • Overview of the Date Object and its capabilities.

2. Creating a Date Object

Example 1: Creating a Date Object
let currentDate = new Date();
console.log(currentDate);
Example 2: Creating a Date Object with Specific Date and Time
let specificDate = new Date('2024-07-17T12:00:00');
console.log(specificDate);
Example 3: Creating a Date Object from a String Representation
let dateString = '2024-07-17';
let dateFromString = new Date(dateString);
console.log(dateFromString);

3. Getting and Setting Date Components

Example 1: Getting Current Date Components
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth(); // 0-based (0 for January)
let day = date.getDate();
console.log(year, month, day);
Example 2: Setting Date Components
let date = new Date();
date.setFullYear(2023);
date.setMonth(11); // December (0-based)
date.setDate(25);
console.log(date);
Example 3: Getting Day of the Week
let date = new Date();
let dayOfWeek = date.getDay(); // 0 for Sunday, 1 for Monday, ..., 6 for Saturday
console.log(dayOfWeek);
Example 4: Getting Hours, Minutes, and Seconds
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
console.log(hours, minutes, seconds);
Example 5: Getting and Setting UTC Date Components
let date = new Date();
let utcYear = date.getUTCFullYear();
let utcMonth = date.getUTCMonth();
let utcDay = date.getUTCDate();
console.log(utcYear, utcMonth, utcDay);

4. Formatting Dates

Example 1: Formatting Date to ISO 8601 Format
let date = new Date();
let isoDateString = date.toISOString();
console.log(isoDateString);
Example 1: Formatting Date to ISO 8601 Format
let date = new Date();
let isoDateString = date.toISOString();
console.log(isoDateString);
Example 2: Custom Date Formatting Function
function formatDate(date) {
  let day = date.getDate();
  let month = date.getMonth() + 1; // Months are zero indexed
  let year = date.getFullYear();
  return `${year}-${month}-${day}`;
}
let date = new Date();
console.log(formatDate(date));
Example 3: Formatting Date for Display
let date = new Date();
let formattedDate = date.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
console.log(formattedDate);
Example 4: Formatting Date Components Separately
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate);
Example 5: Formatting Date with Time Zone Offset
let date = new Date();
let timeZoneOffset = date.getTimezoneOffset();
console.log(timeZoneOffset);
Example 6: Formatting Date with Locale Settings
let date = new Date();
let formattedDate = date.toLocaleDateString('de-DE'); // German locale
console.log(formattedDate);

5. Working with Time Zones

Example 1: Converting Date to UTC
let date = new Date();
let utcDate = date.toUTCString();
console.log(utcDate);
Example 2: Converting UTC Date to Local Time
let utcDateString = '2024-07-17T12:00:00Z';
let utcDate = new Date(utcDateString);
let localDate = utcDate.toLocaleString();
console.log(localDate);
Example 3: Displaying UTC Date in Local Time Zone
let utcDateString = '2024-07-17T12:00:00Z';
let utcDate = new Date(utcDateString);
let localDate = new Date(utcDate.getTime() + (utcDate.getTimezoneOffset() * 60000));
console.log(localDate);
Example 4: Getting Time Zone Offset
let date = new Date();
let timeZoneOffset = date.getTimezoneOffset();
console.log(timeZoneOffset);
Example 5: Displaying Date and Time in Different Time Zones
let date = new Date();
let utcString = date.toISOString();
let utcDate = new Date(utcString);
let localDate = new Date(utcDate.getTime() + (utcDate.getTimezoneOffset() * 60000));
console.log(localDate.toLocaleString());
Example 6: Handling Daylight Saving Time Changes
// Example code to handle daylight saving time changes
// JavaScript Date object automatically adjusts for DST

6. Manipulating Dates

Example 1: Adding Days to a Date
function addDays(date, days) {
  let result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}
let today = new Date();
let futureDate = addDays(today, 7);
console.log(futureDate);
Example 2: Subtracting Days from a Date
function subtractDays(date, days) {
  let result = new Date(date);
  result.setDate(result.getDate() - days);
  return result;
}
let today = new Date();
let pastDate = subtractDays(today, 7);
console.log(pastDate);
Example 3: Adding Months to a Date
function addMonths(date, months) {
  let result = new Date(date);
  result.setMonth(result.getMonth() + months);
  return result;
}
let today = new Date();
let futureMonth = addMonths(today, 3);
console.log(futureMonth);
Example 4: Comparing Two Dates
let date1 = new Date('2024-07-17');
let date2 = new Date('2024-07-18');
if (date1.getTime() === date2.getTime()) {
  console.log('Dates are equal');
} else if (date1.getTime() < date2.getTime()) {
  console.log('date1 is before date2');
} else {
  console.log('date1 is after date2');
}
Example 5: Calculating Age from Birth Date
function calculateAge(birthDate) {
  let today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  if (today.getMonth() < birthDate.getMonth() ||
      (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}
let birthDate = new Date('1990-01-01');
console.log(calculateAge(birthDate));
Example 6: Finding Days Between Two Dates
function daysBetween(date1, date2) {
  const oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
  const diffDays = Math.round(Math.abs((date1 - date2) / oneDay));
  return diffDays;
}
let startDate = new Date('2024-07-01');
let endDate = new Date('2024-07-15');
console.log(daysBetween(startDate, endDate));

7. Best Practices and Considerations

  • Using UTC Methods for Time Zone-agnostic Operations
  • Properly Handling Date Formatting Based on Locale
  • Ensuring Consistent Date Manipulations Across Time Zones

Interview Questions:-

Here are 20 interview questions and answers based on JavaScript Date and Time concepts:
Q1. How do you create a Date object in JavaScript?

Answer: In JavaScript, you create a Date object using the new Date() constructor. For example

Q2. Explain the difference between getMonth() and getUTCMonth() methods in the Date object.

Answer: getMonth() returns the month (0-11) of a local date, while getUTCMonth() returns the month (0-11) of a date according to UTC time.

Q3.How can you get the current date formatted as “YYYY-MM-DD” in JavaScript?

Answer:

let date = new Date();
let formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
console.log(formattedDate);

Q4. Explain how to convert a UTC date string to a local date object in JavaScript.

Answer:

let utcDateString = '2024-07-17T12:00:00Z';
let utcDate = new Date(utcDateString);
let localDate = new Date(utcDate.getTime() + (utcDate.getTimezoneOffset() * 60000));
console.log(localDate);
Q5. How do you format a date for display in different locales using JavaScript?

Answer:

let date = new Date();
let formattedDate = date.toLocaleDateString('fr-FR'); // French locale
console.log(formattedDate);
Q6. How can you get the day of the week from a given date in JavaScript?

Answer

let date = new Date();
let dayOfWeek = date.toLocaleDateString('en-US', { weekday: 'long' });
console.log(dayOfWeek);

Q7. Explain how to add 5 days to the current date in JavaScript.

Answer:

let currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 5);
console.log(currentDate);
Q8. How do you compare two dates in JavaScript?

Answer:

let date1 = new Date('2024-07-17');
let date2 = new Date('2024-07-18');
if (date1.getTime() === date2.getTime()) {
  console.log('Dates are equal');
} else if (date1.getTime() < date2.getTime()) {
  console.log('date1 is before date2');
} else {
  console.log('date1 is after date2');
}
Q9. What is the significance of toISOString() method in JavaScript Date object?

Answer: The toISOString() method returns a string representation of the date in ISO 8601 format (e.g., “2024-07-17T12:00:00.000Z”).

Q10. How can you determine if a given year is a leap year in JavaScript?

Answer:

function isLeapYear(year) {
  return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
console.log(isLeapYear(2024)); // Output: true
11. Explain how to get the current time in milliseconds since January 1, 1970 (Unix Epoch) in JavaScript.

Answer:

let currentTime = Date.now();
console.log(currentTime);
Q12.How can you extract the hour and minute from a given date in JavaScript?

Answer:

let date = new Date();
let hour = date.getHours();
let minute = date.getMinutes();
console.log(`Current time is ${hour}:${minute}`);
Q13. Explain the difference between toLocaleString() and toDateString() methods in the Date object.
  • Answer:
  • toLocaleString() returns a string representing the date and time according to the locale and options specified.
  • toDateString() returns a string representing the date portion of the date object.
Q14.How do you calculate the difference in days between two dates in JavaScript?

Answer:

function daysBetween(date1, date2) {
  const oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
  const diffDays = Math.round(Math.abs((date1 - date2) / oneDay));
  return diffDays;
}
let startDate = new Date('2024-07-01');
let endDate = new Date('2024-07-15');
console.log(daysBetween(startDate, endDate));
Q15. How can you handle time zone differences when displaying dates in a web application?

Answer: Use UTC methods (getUTC*, setUTC*) to perform operations that should be time zone-agnostic, and consider converting dates to local time for display using toLocaleString().

Q16. Explain the concept of Daylight Saving Time (DST) and its impact on JavaScript Date objects.

Answer: Daylight Saving Time is a practice where clocks are adjusted forward in the spring and backward in the fall to make better use of daylight. JavaScript Date objects automatically adjust for DST changes based on the system’s time zone settings.

Q17. How do you handle date input from a user in a specific format (e.g., “YYYY-MM-DD”) and validate it in JavaScript?

Answer:

function isValidDate(dateString) {
  let regex = /^\d{4}-\d{2}-\d{2}$/;
  if (!regex.test(dateString)) return false;
  let date = new Date(dateString);
  return !isNaN(date.getTime());
}
console.log(isValidDate('2024-07-17')); // Output: true
Q18. How can you set the time part of a Date object to midnight (00:00:00) in JavaScript?

Answer:

let date = new Date();
date.setHours(0, 0, 0, 0);
console.log(date);
Q19. What considerations should you take when working with dates across different time zones in a distributed web application?

Answer: Use UTC methods to maintain consistency across time zones, consider displaying dates in local time based on the user’s location, and be aware of potential pitfalls like Daylight Saving Time changes.

Q20. Explain how you would implement a countdown timer in JavaScript using Date objects.

Answer: Use setInterval() to update the timer every second, calculating the difference between the target end time and the current time.

These questions and answers cover a range of JavaScript Date and Time topics, from basic operations to more advanced concepts relevant for interviews. They are designed to assess both fundamental understanding and practical application of handling dates and times in JavaScript.