Your Course Progress

Topics
0 / 0
0.00%
Practice Tests
0 / 0
0.00%
Tests
0 / 0
0.00%
Assignments
0 / 0
0.00%
Content
0 / 0
0.00%
% Completed

JavaScript Date and Its Methods

The Date object in JavaScript is a powerful tool for working with dates and times. It stores the number of milliseconds that have passed since January 1, 1970, 00:00:00 UTC (the Unix Epoch). This representation allows you to perform a wide range of operations, from obtaining the current date and time to manipulating and comparing dates.

JavaScript Date and Its Methods

Introduction to Date Data Type

The Date object in JavaScript is a powerful tool for working with dates and times. It stores the number of milliseconds that have passed since January 1, 1970, 00:00:00 UTC (the Unix Epoch). This representation allows you to perform a wide range of operations, from obtaining the current date and time to manipulating and comparing dates.

let currentDate = new Date();
    console.log(currentDate); // Displays the current date and time

You can create Date objects using various constructors, depending on the specific date and time you want to represent.

let now = new Date();
    console.log(now); // Current date and time
let specificDate = new Date('December 25, 2024 12:00:00');
    console.log(specificDate); // Wed Dec 25 2024 12:00:00
let newDate = new Date(2024, 11, 25, 12, 0, 0); // Month is 0-indexed (11 = December)
    console.log(newDate); // Wed Dec 25 2024 12:00:00
let dateFromMillis = new Date(0); // 0 milliseconds = Jan 1, 1970
    console.log(dateFromMillis); // Thu Jan 01 1970 00:00:00

JavaScript provides a wide range of methods for working with Date objects. These methods allow you to retrieve date and time components, set new values, compare dates, format dates, and work with dates in different time zones.

  • getFullYear(): Returns the 4-digit year.
  • getMonth(): Returns the month (0-11, where 0 is January and 11 is December).
  • getDate(): Returns the day of the month (1-31).
  • getHours(), getMinutes(), getSeconds(), getMilliseconds(): Return the respective time components.
  • getDay(): Returns the day of the week (0-6, where 0 is Sunday and 6 is Saturday).
let year = new Date().getFullYear();
    console.log(year); // 2024
    
    let month = new Date().getMonth();
    console.log(month); // 9 (October)
    
    let day = new Date().getDate();
    console.log(day); // 11
    
    let now = new Date();
    console.log(now.getHours()); // e.g., 14 (2 PM)
    console.log(now.getMinutes()); // e.g., 30
    
    let weekday = new Date().getDay();
    console.log(weekday); // e.g., 5 (Friday)
  • setFullYear(year): Sets the year of the date.
  • setMonth(month): Sets the month (0-11).
  • setDate(day), setHours(), setMinutes(), setSeconds(), setMilliseconds(): Set the respective time components.
let d = new Date();
    d.setFullYear(2025);
    console.log(d); // Year is now 2025
    
    d = new Date();
    d.setMonth(5); // June
    console.log(d); // Month is now June
    
    d = new Date();
    d.setDate(15); // Set day to 15th
    d.setHours(10); // Set hour to 10 AM
    console.log(d); // Date with new day and time
  • getTime(): Returns the number of milliseconds since the Unix Epoch (January 1, 1970).
  • valueOf(): Same as getTime(), returns the primitive value of the Date object.
let timeMillis = new Date().getTime();
    console.log(timeMillis); // e.g., 1736340960223
    
    let timeValue = new Date().valueOf();
    console.log(timeValue); // e.g., 1736340960223

You can compare dates using standard comparison operators (<, >, <=, >=).

let date1 = new Date('2024-10-10');
    let date2 = new Date();
    console.log(date1 > date2); // true or false depending on the current date
  • toDateString(): Returns the date portion as a human-readable string.
  • toLocaleDateString(): Returns a locale-specific string representation of the date.
  • toISOString(): Returns the date as a string in ISO 8601 format.
let date = new Date();
    console.log(date.toDateString()); // e.g., "Fri Oct 11 2024"
    
    console.log(date.toLocaleDateString('en-US')); // "10/11/2024" for US format
    
    console.log(date.toISOString()); // "2024-10-11T14:00:00.000Z"

JavaScript allows you to work with dates in UTC time instead of the local time zone. This is useful when dealing with dates that need to be consistent regardless of the user's location.

Do You Know?

UTC stands for Coordinated Universal Time, which is a globally recognized standard for time keeping.

  • getUTCFullYear(), getUTCMonth(), getUTCDate(): Get the date components in UTC time.
  • setUTCFullYear(), setUTCMonth(), etc.: Set the date components in UTC time.
let now = new Date();
    console.log(now.getUTCFullYear()); // 2024
    console.log(now.getUTCMonth()); // 9 (October)
    console.log(now.getUTCDate()); // 11
    
    let d = new Date();
    d.setUTCFullYear(2025);
    console.log(d.toUTCString()); // Date with year set to 2025 in UTC

If you create a Date object with invalid values, it will return "Invalid Date".

let invalid = new Date('invalid-date');
    console.log(invalid); // Invalid Date

If a date operation results in a non-numeric value (e.g., subtracting two non-date objects), it will return NaN.

let invalidOp = new Date() - 'hello';
    console.log(invalidOp); // NaN

Date objects allow for basic arithmetic operations, such as adding or subtracting days, months, or years. You can achieve this by using the methods that set specific date components.

let date = new Date();
    date.setDate(date.getDate() + 5); // Add 5 days to the current date
    console.log(date);
let date = new Date();
    date.setMonth(date.getMonth() - 2); // Subtract 2 months from the current date
    console.log(date);
Important Note

Remember that adding or subtracting months can lead to unexpected behavior if the target month has fewer days than the starting month. For example, adding a month to February 29th in a leap year will result in March 29th (which doesn't exist), so JavaScript will adjust the date accordingly.

The Date object in JavaScript is a versatile tool that empowers you to work with dates and times effectively. By understanding the fundamental concepts and mastering the various methods, you'll gain the ability to manipulate and format dates, handle time zones, and perform date calculations with precision.

Key Takeaways
  • The Date object stores the number of milliseconds since the Unix Epoch.
  • You can create Date objects for specific dates, current date and time, or from milliseconds.
  • Methods like getFullYear(), getMonth(), getDate(), etc., allow you to retrieve individual date and time components.
  • Methods like setFullYear(), setMonth(), setDate(), etc., enable you to set new values for date and time components.
  • Date objects support comparison using operators like <, >, <=, >=.
  • You can format dates using methods like toDateString(), toLocaleDateString(), and toISOString().
  • JavaScript provides methods for working with UTC dates.
  • Be mindful of special cases like "Invalid Date" and NaN in date operations.
  • Date calculations are possible using methods that set specific date components.

Discussion