Sunday, December 3, 2023
HomeVideo EditingUse JavaScript APIs to Get the Present Date and Time

Use JavaScript APIs to Get the Present Date and Time


JavaScript gives APIs that allow builders to simply work with dates, occasions, and time zones. On this article, we are going to have a look at how one can use JavaScript’s Date and Time APIs to get the present date and time, format them, and carry out different actions.

Introduction to Date and Time in JavaScript

Coping with date and time in net growth is inescapable. It’s used on quite a lot of on-line purposes for displaying dates and occasions, countdown timers, timestamps, scheduling occasions, and dealing with customers’ interactions with time components. JavaScript has an in-built Date object that’s the key device for working with date and time.

Have you ever ever been on a website, like an e-commerce website and there’s an merchandise on show at a reduced worth for a restricted period of time? Or a countdown timer on a restaurant web site for a launch opening? Or an animation on an internet site that’s being timed? These and lots of extra are some examples of situations the place date and time APIs are getting used for net growth.

Getting the Present Date and Time

Now how can we make the most of this in-built date object in JavaScript to get the present date and time? It is fairly easy. All you could do is to create a brand new occasion of the Date object with none arguments to get the present date and time. Subsequent log the present date and time to the console.

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

This can log the present date and time onto your console on this format: `day-month-date-year hour-minute-second timezone`. This, for instance, Tue Jul 25 2023 12:37:10 GMT+0100 (West Africa Commonplace Time)

The Date object additionally gives strategies for extracting particular person parts of date and time akin to 12 months, month, day, hour, minute, second, GMT, and time zone. This is an instance:

1
const currentDate = new Date();
2
const 12 months = 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(`12 months: ${12 months}`);
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 brand new Date object with the present date and time. It then makes use of numerous strategies of the Date object, akin to getFullYear(), getMonth(),getHours(), and getMinutes() to extract some particular person parts of the date and time. We additionally did a bit of calculation to get the timezone. If you run this code, you will see the present 12 months, month, hour, minute, and time zone printed on the console. Remember that the outcomes will rely upon the present date and time when and the place the code is executed.

Formatting the Date and Time

Date and time in JavaScript will also be formatted to fulfill particular wants. The “Date” object used above gives strategies for extracting particular person parts of date and time and implementing fundamental functionalities. To format date and time to fulfill particular wants, nevertheless, requires some extra steps. There are some JS libraries that can be utilized to format date and time and so they embrace Second.js, Luxon.js, Date-fns, Day.js, and some extra. On this part, we’ll be looking in the intervening time.js library.

To begin utilizing the second.js library, you could embrace it in your mission. You are able to do so by utilizing any of the two strategies talked about under:

  1. Putting in it with npm by typing this command into your terminal or command line: npm set up second
  2. Linking it to your mission from CDN. To hyperlink second.js to your mission, add this to the pinnacle tag of your HTML file: <script src=”https://cdnjs.cloudflare.com/ajax/libs/second.js/2.29.1/second.min.js”></script>
1
const currentDate = new Date();
2
const formattedDateTime = second(currentDate).format("YYYY-MM-DD HH:mm:ss");
3
console.log(formattedDateTime);

The output for that is 2023-07-25 13:04:38 (the date and time output is on the time I ran the code). The format operate in second.js accepts numerous formatting strings to customise the output as desired. On this case, we formatted it to show solely the 12 months, month, day, hour, minute, and second.

One other instance to show the usage of the second.js library is.

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

What these strains of code do is that:

  • Within the first line of code, it makes use of the second() operate from the library to create a brand new second object representing the present date and time. Theadd() technique is then known as on this second object so as to add 5 minutes to it. The first argument handed to the add() technique is the variety of models so as to add. The 2nd argument being handed is the unit of time so as to add (on this case, ‘minutes’).
  • The second line of code is the code to log the formatted date and time to the browser console. The format() technique known as on the brand new second object created within the earlier line. It takes a string as an argument to specify the format we wish the date and time to be displayed in. The format, on 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 instance, for example the time is 5:30 and we add 5 minutes to it, the time will then be 5:35.
  • The third line of code is sort of much like the primary but it surely performs a special operation. It makes use of the second() operate from the library to create a brand new second object representing the present date and time. The subtract() technique is then known as on this second object to subtract 3 days from it. Just like the add() technique, the first argument being handed to the subtract() technique is the variety of models to subtract. The 2nd argument being handed is the unit of time to subtract (on this case, ‘days’).
  • Within the fourth line of code, we log the formatted date and time to the console. The format() technique known as on the newly created second object and it takes a string as an argument to specify the format we wish to show the date. The format we specified is ‘dddd, MMMM Do YYYY‘. The “dddd” represents the complete weekday title, “MMMM” represents the complete month title, the “Do” represents the day of the month with a suffix, and “YYYY” represents the 12 months. So for example the present date is July twenty fifth, 2023 and we subtract 3 days from it, the date will then be ‘Saturday, July twenty second, 2023’.

A fast abstract of this can be a demonstration of how second.js can be utilized to control date and time in JavaScript.

Time zone Dealing with

Accurately dealing with time zones is essential for apps that work together with customers from many nations. By default, the Date object in JavaScript makes use of the consumer’s system time zone. What it would not do, nevertheless, is supply direct help for working with particular time zones. Make the most of the Intl.DateTimeFormat object from the ECMAScript Internationalisation API (ECMA-402) to effectively handle time zones. The format enables you to show date and time info in a localized format, together with time zone information.

This is a fast demo on how one can present the present date and time in a specific 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: 'lengthy', timeZone: 'lengthy', timeZone: 'Australia/Sydney' }).format(date));

  • The primary line of code creates a brand new Date object named date representing the date and time.
  • Within the second line of code, we use the Intl.DateTimeFormat object to format the date within the US English locale. The format() technique is used to format the date object, and it then returns a string illustration of the formatted date. Within the US English locale, the format is month-day-year order. So, the output shall be 7/25/2023.
  • Identical factor for the third line of code, however on this case, we’re formatting the date within the British English locale. The format is day-month-year order. So, the output shall be 25/07/2023.
  • The fourth line makes use of the Intl.DateTimeFormat object with choices to format the date within the British English locale and the time zone set to ‘Australia/Sydney’. The ‘dateStyle’ choice is ready to “full”, and the ‘timeStyle’ choice is ready to “lengthy.” The ‘full’ date model gives the complete textual illustration of the date, and the “lengthy” time model gives the lengthy textual illustration of the time. The ‘timeZone’ choice is ready to “Australia/Sydney”, which implies the date and time shall be displayed within the time zone of Sydney, Australia.

The output shall be one thing like this: Tuesday, 25 July 2023 at 13:00:00 GMT+10. The precise output may differ relying in your present time zone.

Observe that within the instance above we used “6” to signify the month of July as an alternative of “7” which is the month place it stands for. Nicely, it’s because, in JavaScript, the month parameter for the Date object (and consequently the Intl.DateTimeFormat object) is zero-based, which means January is represented by 0, February by 1, and so forth. Due to this fact, to signify July, you need to use 6 as an alternative of seven, and for August, you need to use 7 as an alternative of 8.

Performing Date and Time Operations

The Date object in JavaScript gives a number of strategies for performing date and time operations, akin to computing the distinction between two dates, including or eradicating time intervals, and evaluating dates. Some often used strategies are: getTime(), setTime(), getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), and getSeconds(). These operations are important for duties like calculating durations, setting deadlines, and dealing with time-related logic in purposes. 

This is an instance of how one can calculate the distinction 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.ground(timeDifference / (1000 * 60 * 60 * 24));
5
console.log(`The times distinction is: ${daysDifference}`);

Code clarification:

  • The primary line of code creates a brand new Date object representing the date July 1, 2023. The Date constructor is used with a date string within the format “YYYY-MM-DD” to specify the specified begin date.
  • One other new Date object representing the date July 17, 2023, can also be created with a specified format for the tip date.
  • The third line of code is to calculate the variations between the two newly created date objects – “endDate” and “startDate”. The getTime() technique is used to get the time worth of every Date object. By subtracting the startDate time worth from the endDate time worth, we acquire the time distinction between the 2 dates in milliseconds.
  • The fourth line of code: To calculate the distinction between the 2 dates, divide the “timeDifference” (in milliseconds) by the variety of milliseconds in a day which is 1000 milliseconds multiplied by 60 seconds multiplied by 60 minutes multiplied by 24 hours. The outcome then is the distinction in days between the 2 dates. The Math.ground() operate is used to spherical down the outcome to the closest integer, to make sure that we get a complete quantity representing the times.
  • The fifth line of code logs the “daysDifference” to the console. The output would be the variety of days between the startDate and endDate. On this instance, the output shall be The times distinction is: 16, indicating that there are 16 days between July 1, 2023, and July 17, 2023.

In abstract, the code pattern makes use of the Date object and easy arithmetic operations to calculate the distinction in days between two supplied dates (startDate and endDate). This may be helpful for many date-related computations, akin to figuring out the period between two occasions or the variety of days earlier than a given deadline.

Abstract

On this article, we emphasised the use and significance of the Date and Time APIs in JavaScript for net growth. For formatting dates and occasions, we additionally demonstrated how one can use JavaScript’s built-in Date object and the second.js library. Moreover, we highlighted the necessity to successfully deal with time zones for purposes having customers from completely different geographical areas. 

Conclusion

On this article, we explored numerous elements of working with date and time in JavaScript. We mentioned how one can carry out frequent date and time calculations, together with including and subtracting time intervals, evaluating dates, and calculating variations between dates. We additionally explored the favored Second.js library, which gives extra options for working with dates and occasions. This text additionally confirmed us how one can format dates and occasions utilizing the Intl.DateTimeFormat object.

Lastly, studying the Date and Time APIs in JavaScript permits builders to create highly effective, user-friendly, and time-sensitive apps in quite a lot of fields, starting from easy time shows to timer countdown to advanced scheduling, and occasion dealing with. Understanding how one can work with date and time information effectively is a vital talent for any JavaScript developer, and it could actually considerably increase the performance and usefulness of their apps.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments