1. Code
  2. JavaScript

Use JavaScript APIs to Get the Current Date and Time

Scroll to top
10 min read

JavaScript provides APIs that enable developers to easily work with dates, times, and time zones. In this article, we will look at how to use JavaScript's Date and Time APIs to get the current date and time, format them, and perform other actions.

Introduction to Date and Time in JavaScript

Dealing with the date and time in web development is inescapable. It is used in a variety of online applications for displaying dates and times, countdown timers, and time stamps, as well as scheduling events and handling users' interactions with time elements. JavaScript has a built-in Date object that is the key tool for working with date and time.

Have you ever been on a site, like an eCommerce site, where there's an item on display at a discounted price for a limited amount of time? Or a countdown timer on a restaurant website for a launch opening? Or an animation on a website that is being timed? These are some examples of the many scenarios in which date and time APIs are being used for web development.

Getting the Current Date and Time

Now how do we use this built-in Date object in JavaScript to get the current date and time? It's quite simple. All you need to do is to create a new instance of the Date object without any arguments to get the current date and time. Next, log the current date and time to the console.

1
const currentDate = new Date();
2
console.log(currentDate);

This will log the current date and time onto your console in this format: day-month-date-year hour-minute-second timezone. This, for example: Tue Jul 25 2023 12:37:10 GMT+0100 (West Africa Standard Time).

The Date object also provides methods for extracting individual components of date and time such as year, month, day, hour, minute, second, GMT, and time zone. Here's an example:

1
const currentDate = new Date();
2
const year = currentDate.getFullYear();
3
const month = currentDate.getMonth() + 1;
4
const hour = currentDate.getHours();
5
const minute = currentDate.getMinutes();
6
const timezoneOffsetHours = gmtOffsetInMinutes / -60;
7
const timezoneOffsetString = timezoneOffsetHours >= 0 ? `+${timezoneOffsetHours}` : `-${Math.abs(timezoneOffsetHours)}`;
8
9
console.log(`Year: ${year}`);
10
console.log(`Month: ${month}`);
11
console.log(`Hour: ${hour}`);
12
console.log(`Minute: ${minute}`);
13
console.log(`Timezone Offset: GMT${timezoneOffsetString}`);

This code creates a new Date object with the current date and time. It then uses various methods of the Date object, such as getFullYear(), getMonth(), getHours(), and getMinutes(), to extract individual components of the date and time. We also do a little calculation to get the time zone. When you run this code, you'll see the current year, month, hour, minute, and time zone printed on the console. Keep in mind that the results will depend on the current date and time when and where the code is executed.

Formatting the Date and Time

Date and time in JavaScript can also be formatted to meet specific needs. The Date object used above provides methods for extracting individual components of date and time and implementing basic functionalities. To format the date and time to meet specific needs, however, requires some additional steps. There are some JavaScript libraries that can be used to format date and time, and they include Moment.js, Luxon.js, Date-fns, Day.js, and a few more. In this section, we'll be taking a look at the Moment.js library.

To start using the Moment.js library, you need to include it in your project. You can do so by using either of these two methods:

  1. Installing it with npm by typing this command into your terminal or command line: npm install moment
  2. Linking it to your project from CDN. To link Moment.js to your project, add this to the head tag of your HTML file: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
1
const currentDate = new Date();
2
const formattedDateTime = moment(currentDate).format("YYYY-MM-DD HH:mm:ss");
3
console.log(formattedDateTime);

The output for this is 2023-07-25 13:04:38 (the date and time output is at the time I ran the code). The format function in Moment.js accepts various formatting strings to customize the output as desired. In this case, we formatted it to display only the year, month, day, hour, minute, and second.

Another example to demonstrate the use of the Moment.js library is:

1
const addMinutes = moment().add(5, 'minutes');
2
console.log(`${addMinutes.format('h:mm a')}`);
3
const subtractDays = moment().subtract(3, 'days');
4
console.log(`${subtractDays.format('dddd, MMMM Do YYYY')}`)

Here's what these lines of code do:

  • The first line of code uses the moment() function from the library to create a new moment object representing the current date and time. The add() method is then called on this moment object to add 5 minutes to it. The first argument passed to the add() method is the number of units to add. The second argument being passed is the unit of time to add (in this case, 'minutes').
  • The second line of code is the code to log the formatted date and time to the browser console. The format() method is called on the new moment object created in the previous line. It takes a string as an argument to specify the format we want the date and time to be displayed in. The format, in this case, is: 'h:mm a'. "h" represents the hour, "mm" represents the minutes in 12-hour clock format, and the "a" represents the AM/PM designation. For example, if the time is 5:30 and we add five minutes to it, the time will then be 5:35.
  • The third line of code is quite similar to the first, but it performs a different operation. It uses the moment() function from the library to create a new moment object representing the current date and time. The subtract() method is then called on this moment object to subtract 3 days from it. Like the add() method, the first argument being passed to the subtract() method is the number of units to subtract. The second argument being passed is the unit of time to subtract (in this case, 'days').
  • In the fourth line of code, we log the formatted date and time to the console. The format() method is called on the newly created moment object, and it takes a string as an argument to specify the format in which we want to display the date. The format we specified is 'dddd, MMMM Do YYYY'. The "dddd" represents the full weekday name, "MMMM" represents the full month name, "Do" represents the day of the month with a suffix, and "YYYY" represents the year. So let's say the current date is July 25th, 2023 and we subtract 3 days from it. The date will then be 'Saturday, July 22nd, 2023'.

This is a quick demonstration of how Moment.js can be used to manipulate date and time in JavaScript.

Time-Zone Handling

Correctly handling time zones is critical for apps that interact with users from many countries. By default, the Date object in JavaScript utilizes the user's system time zone. What it doesn't do, however, is offer direct support for working with specific time zones. Use the Intl.DateTimeFormat object from the ECMAScript Internationalisation API (ECMA-402) to efficiently manage time zones. The format lets you display date and time information in a localized format, including time-zone data.

Here's a quick demo of how to show the current date and time in a particular time zone:

1
const date = new Date(Date.UTC(2023, 6, 25, 3, 0, 0));
2
console.log(new Intl.DateTimeFormat("en-US").format(date));
3
console.log(new Intl.DateTimeFormat("en-GB").format(date));
4
console.log(new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long', timeZone: 'long', timeZone: 'Australia/Sydney' }).format(date));
  • The first line of code creates a new Date object named date representing the date and time.
  • In the second line of code, we use the Intl.DateTimeFormat object to format the date in the US English locale. The format() method is used to format the date object, and it then returns a string representation of the formatted date. In the US English locale, the format is month-day-year order. So the output will be 7/25/2023.
  • It's the same thing for the third line of code, but in this case, we are formatting the date in the British English locale. The format is day-month-year order. So the output will be 25/07/2023.
  • The fourth line uses the Intl.DateTimeFormat object, with options to format the date in the British English locale and the time zone set to 'Australia/Sydney'. The 'dateStyle' option is set to "full", and the 'timeStyle' option is set to "long." The 'full' date style provides the full textual representation of the date, and the "long" time style provides the long textual representation of the time. The 'timeZone' option is set to "Australia/Sydney", which means the date and time will be displayed in the time zone of Sydney, Australia.

The output will be something like this: Tuesday, 25 July 2023 at 13:00:00 GMT+10. The actual output might vary depending on your current time zone.

Note that in the example above, we used "6" to represent the month of July instead of "7", which is the month position it stands for. This is because, in JavaScript, the month parameter for the Date object (and consequently the Intl.DateTimeFormat object) is zero-based, meaning January is represented by 0, February by 1, and so on. Therefore, to represent July, you should use 6 instead of 7, and for August, you should use 7 instead of 8.

Performing Date and Time Operations

The Date object in JavaScript provides several methods for performing date and time operations, such as computing the difference between two dates, adding or removing time intervals, and comparing dates. Some regularly used methods are getTime(), setTime(), getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), and getSeconds(). These operations are essential for tasks like calculating durations, setting deadlines, and handling time-related logic in applications. 

Here's an example of how you can calculate the difference between two dates:

1
const startDate = new Date("2023-07-01");
2
const endDate = new Date("2023-07-17");
3
const timeDifference = endDate.getTime() - startDate.getTime();
4
const daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
5
console.log(`The days difference is: ${daysDifference}`);

Code Explanation

  • The first line of code creates a new Date object representing the date July 1, 2023. The Date constructor is used with a date string in the format "YYYY-MM-DD" to specify the desired start date.
  • Another new Date object representing the date July 17, 2023, is also created with a specified format for the end date.
  • The third line of code is to calculate the differences between the two newly created date objects: "endDate" and "startDate". The getTime() method is used to get the time value of each Date object. By subtracting the startDate time value from the endDate time value, we obtain the time difference between the two dates in milliseconds.
  • The fourth line of code: To calculate the difference between the two dates, divide the "timeDifference" (in milliseconds) by the number of milliseconds in a day, which is 1000 milliseconds multiplied by 60 seconds multiplied by 60 minutes multiplied by 24 hours. The result then is the difference in days between the two dates. The Math.floor() function is used to round down the result to the nearest integer, to ensure that we get a whole number representing the days.
  • The fifth line of code logs the "daysDifference" to the console. The output will be the number of days between the startDate and endDate. In this example, the output will be The days difference is: 16, indicating that there are 16 days between July 1, 2023, and July 17, 2023.

In summary, the code sample uses the Date object and simple arithmetic operations to calculate the difference in days between two provided dates (startDate and endDate). This can be useful for lots of date-related computations, such as determining the duration between two events or the number of days before a given deadline.

Conclusion

In this article, we explored various aspects of working with date and time in JavaScript. We discussed how to perform common date and time calculations, including adding and subtracting time intervals, comparing dates, and calculating differences between dates. We also explored the popular Moment.js library, which provides additional features for working with dates and times. This article also showed us how to format dates and times using the Intl.DateTimeFormat object.

Finally, learning the Date and Time APIs in JavaScript enables developers to create powerful, user-friendly, and time-sensitive apps in a variety of fields, ranging from simple time displays to timer countdown to complex scheduling, and event handling. Understanding how to work with date and time data efficiently is a necessary skill for any JavaScript developer, and it can significantly boost the functionality and usability of your apps.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.