10 - JavaScript - Dates

10 - JavaScript - Dates

JavaScript dates are a way to represent and work with date and time values in JavaScript. Dates in JavaScript are represented using the built-in Date object, which contains methods for working with dates and times.

Dates in JavaScript are stored as the number of milliseconds since January 1, 1970, 00:00:00 UTC, which is also known as the Unix Epoch. This value is often referred to as a timestamp.

To create a new Date object in JavaScript, you can simply call the Date constructor with no arguments, which will create a new Date object representing the current date and time. You can also create a new Date object by passing in a string or a number representing a timestamp.

Once you have a Date object, you can use its methods to get and set various properties of the date and time, such as the year, month, day, hour, minute, second, and millisecond. You can also perform various operations on dates, such as calculating the difference between two dates, adding or subtracting a certain amount of time, and formatting the date and time as a string.

JavaScript Date Formats

There are several ways to format dates in JavaScript, including built-in methods and third-party libraries. Here are some of the most common date formats and examples of how to use them -

  1. ISO Date (YYYY-MM-DD) The ISO date format is widely used in databases and APIs. To format a date in this format in JavaScript, you can use the toISOString() method:

     const date = new Date();
     const isoDate = date.toISOString().slice(0,10);
     console.log(isoDate); // Output: 2023-04-15
    
  2. Short Date (MM/DD/YYYY) The short date format is commonly used in the United States. To format a date in this format in JavaScript, you can use the toLocaleDateString() method:

     const date = new Date();
     const shortDate = date.toLocaleDateString('en-US');
     console.log(shortDate); // Output: 4/15/2023
    
  3. Long Date (Month DD, YYYY) The long date format is commonly used in written documents. To format a date in this format in JavaScript, you can use the toLocaleDateString() method with the options parameter:

     const date = new Date();
     const options = { year: 'numeric', month: 'long', day: 'numeric' };
     const longDate = date.toLocaleDateString('en-US', options);
     console.log(longDate); // Output: April 15, 2023
    
  4. Time (HH:MM:SS) To format a time in JavaScript, you can use the toLocaleTimeString() method:

     const date = new Date();
     const time = date.toLocaleTimeString();
     console.log(time); // Output: 10:30:25 AM
    
  5. DateTime (MM/DD/YYYY HH:MM:SS) To format a date and time in JavaScript, you can combine the toLocaleDateString() and toLocaleTimeString() methods:

     const date = new Date();
     const dateTime = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
     console.log(dateTime); // Output: 4/15/2023 10:30:25 AM
    
  6. Custom Date Formats If none of the built-in formats meet your needs, you can create a custom format using the Intl.DateTimeFormat() constructor:

     const date = new Date();
     const formatter = new Intl.DateTimeFormat('en-US', {
       weekday: 'long',
       year: 'numeric',
       month: 'long',
       day: 'numeric',
       hour: 'numeric',
       minute: 'numeric',
       second: 'numeric',
       timeZoneName: 'short'
     });
     const customDate = formatter.format(date);
     console.log(customDate); // Output: Saturday, April 15, 2023 at 10:30:25 AM PDT
    

    In this example, we're creating a custom date format that includes the weekday, year, month, day, hour, minute, second, and time zone name. The Intl.DateTimeFormat() constructor takes two arguments: the locale and an options object that specifies the desired format. The resulting string is generated using the format() method.

JavaScript Date Get Methods

There are several built-in methods in JavaScript for getting different parts of a date object. Here are some of the most common methods for getting date values -

  1. getFullYear() The getFullYear() method returns the four-digit year of the specified date.

     const date = new Date();
     const year = date.getFullYear();
     console.log(year); // Output: 2023
    
  2. getMonth() The getMonth() method returns the zero-indexed month of the specified date (0 for January, 1 for February, and so on).

     const date = new Date();
     const month = date.getMonth();
     console.log(month); // Output: 3 (for April)
    
  3. getDate() The getDate() method returns the day of the month (1-31) of the specified date.

     const date = new Date();
     const day = date.getDate();
     console.log(day); // Output: 15
    
  4. getDay() The getDay() method returns the zero-indexed day of the week (0 for Sunday, 1 for Monday, and so on) of the specified date.

     const date = new Date();
     const dayOfWeek = date.getDay();
     console.log(dayOfWeek); // Output: 6 (for Saturday)
    
  5. getHours() The getHours() method returns the hour (0-23) of the specified date.

     const date = new Date();
     const hours = date.getHours();
     console.log(hours); // Output: 10
    
  6. getMinutes() The getMinutes() method returns the minute (0-59) of the specified date.

     const date = new Date();
     const minutes = date.getMinutes();
     console.log(minutes); // Output: 30
    
  7. getSeconds() The getSeconds() method returns the second (0-59) of the specified date.

     const date = new Date();
     const seconds = date.getSeconds();
     console.log(seconds); // Output: 25
    
  8. getMilliseconds() The getMilliseconds() method returns the millisecond (0-999) of the specified date.

     const date = new Date();
     const milliseconds = date.getMilliseconds();
     console.log(milliseconds); // Output: 471
    

JavaScript Date Set Methods

There are several built-in methods in JavaScript for setting different parts of a date object. Here are some of the most common methods for setting date values -

  1. setFullYear() The setFullYear() method sets the year of the specified date.

     const date = new Date();
     date.setFullYear(2022);
     console.log(date); // Output: Tue Apr 15 2022 10:30:25 GMT+0530 (India Standard Time)
    
  2. setMonth() The setMonth() method sets the zero-indexed month of the specified date (0 for January, 1 for February, and so on).

     const date = new Date();
     date.setMonth(5);
     console.log(date); // Output: Fri Jun 15 2023 10:30:25 GMT+0530 (India Standard Time)
    
  3. setDate() The setDate() method sets the day of the month (1-31) of the specified date.

     const date = new Date();
     date.setDate(25);
     console.log(date); // Output: Sun Apr 25 2023 10:30:25 GMT+0530 (India Standard Time)
    
  4. setHours() The setHours() method sets the hour (0-23) of the specified date.

     const date = new Date();
     date.setHours(13);
     console.log(date); // Output: Sat Apr 15 2023 13:30:25 GMT+0530 (India Standard Time)
    
  5. setMinutes() The setMinutes() method sets the minute (0-59) of the specified date.

     const date = new Date();
     date.setMinutes(45);
     console.log(date); // Output: Sat Apr 15 2023 10:45:25 GMT+0530 (India Standard Time)
    
  6. setSeconds() The setSeconds() method sets the second (0-59) of the specified date.

     const date = new Date();
     date.setSeconds(40);
     console.log(date); // Output: Sat Apr 15 2023 10:30:40 GMT+0530 (India Standard Time)
    
  7. setMilliseconds() The setMilliseconds() method sets the millisecond (0-999) of the specified date.

     const date = new Date();
     date.setMilliseconds(500);
     console.log(date); // Output: Sat Apr 15 2023 10:30:25 GMT+0530 (India Standard Time) + 500 milliseconds
    

Summarizing Up

In summary, JavaScript has built-in support for working with date and time values using the Date object. This object provides various methods for getting and setting different parts of a date, such as year, month, day, hour, minute, second, and millisecond.

Different date formats are available in JavaScript, including ISO, UTC, and local time formats. The ISO format is a widely accepted standard for representing date and time values, and the UTC format is a standardized global time reference.

The getTime() method returns the Unix timestamp of a specified date object, which represents the number of milliseconds since January 1, 1970, 00:00:00 UTC. The Date.parse() method parses a string representation of a date and returns its Unix timestamp.

In addition to the above methods, JavaScript also provides methods for adding and subtracting time intervals from a date, comparing dates, and formatting dates as strings. By using these methods, you can work with date and time values in your JavaScript applications with ease.

Did you find this article valuable?

Support Bosonique ITEdTech by becoming a sponsor. Any amount is appreciated!