Working with Time Data in JavaScript

Michael Capecci
Jul 23 · 5 min read
Image for post
Image for post
Photo by Brad Neathery on Unsplash

A while back, I was writing a CRUD application that kept track of a “start time” and “end time” for entries that were created and stored in a database. I could subtract these time values to find a simple “length of time” for each entry. But retrieving the time data in a useful format was a bit more difficult than I expected.

Date and Time Gotchas

The hardest part of dealing with time data is the likelihood that an edge case is going to throw your application for a loop. Things like localization, 24-hour vs 12-hour time, and other topics present interesting challenges.

In my application, one difficult concept was making it possible for the user to create an entry that lasted for over 24 hours. Working within the constraints of an AM / PM format can pose a significant challenge on its own.

The following micro-project is intended to put on display some of the helpful things I’ve discovered about working with timestamps in JavaScript, and particularly in terms of calculating the value of a passage of time.

Setting Up the Project

This is a very basic project, and there is only minimal CSS that I won’t include here.

The HTML sets up a basic calculator outline with two datetime-local inputs.

The JavaScript is as follows:

The project looks like this so far:

Image for post
Image for post

Project Explanation

1. Retrieve Time String with HTML Input

The HTML <input type=’datetime-local’> does most of the heavy lifting for localization. This will create a calendar-like input that includes a time field in either 12 or 24-hour format depending on the defaults of the user’s operating system.

Image for post
Image for post

When you retrieve the value of the input in JavaScript, you will have access to a string that looks like the following:

2020-07-21T16:20

2. Convert Date String into a Unix Timestamp (milliseconds since 01/01/1970)

The callback function that fires when the Calculate button is clicked is going to translate the date string associated with your time inputs into a number value.

We have created a variable that corresponds with the values of each of the input fields. We then create a new Date object for each of these values, and pass in the values to create the date. Then, we use the .getTime() method built into the Date object to convert our strings into a Unix timestamp.

This timestamp is highly malleable and will bypass many of the gotchas regarding the handling of time data. This number is referred to as either Unix time or Epoch time, and in JavaScript, it represents the number of milliseconds that have passed since the beginning of 1970.

The reason this is awesome is that dealing with time data in the format of a string, object, or other data type is going to present significant challenges when the edge cases of your application start cropping up. If your application is configured from the ground up to accept time data exclusively in Unix format, you can easily manipulate your Unix data as necessary to display useful information to the user. We will do this in the next step.

3. Manipulate Unix Timestamp for the Front End

In the case of this project, and the CRUD application that I talked about earlier, I want to show the user the number of hours that have passed from the start time to the end time.

This comes down to a basic calculation of subtracting the Unix value of the end time by the Unix value of the start time. This will result in a difference of milliseconds that we can divide by the number of milliseconds in an hour (3,600,000). Finally, we can further clean things up by rounding to the second decimal place with .toFixed(2).

After this calculation is complete, we update the value of our “result” element to display the number of hours that have passed on the front end.

4. Adding Basic Validation

The variables within our callback function are going to represent number values based on the string that is passed to their respective Date objects. If they are not able to do so, NaN will be returned.

Thus, we will check to make sure neither field returns NaN and exit the function with an alert if either one does. We will also check to make sure that our end time is a later value than our start time.

That’s basically all that this project does, and the finished product with a calculated result will look as follows:

Image for post
Image for post
Calculator with an accurate calculation on display

Applying this in Other Scenarios

The beautiful thing about working with Unix time data is how universally malleable it is. In most cases, it bypasses limitations set forth by localization, user time display preferences, and other situations that are challenging to manage.

Important Caveat about Storing Time Data

This project serves as a very simple demonstration of using time data in JavaScript, but it does not cover some of the important aspects of storing and displaying that data for later use. When JavaScript converts a time string to Unix time, it will use UTC. This is usually in your best interest as it is beneficial to have all your time data stored as UTC, but there will be an additional step for displaying that data in a useful time format depending on the location of your users.

In other words, store the data in UTC, and convert the front end representation of that data to the local time of the user.

Key Takeaway

Working with dates and times in JavaScript (and any programming language) comes with a lot of “gotchas”. When you start factoring in any sort of complex functionality that your app may require, you may want to consider implementing Unix time to save yourself from many administrative headaches.

I’d love to know if you have any other suggestions on how to deal with time in JavaScript, so please let me know if I’m missing out on something cool.

Thanks for reading.

JavaScript In Plain English

Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Michael Capecci

Written by

Freelance Developer from Chicago, IL. I am focusing on building cool stuff with Gatsby, WordPress and Shopify. Need help with a project? > michaelcapecci.com

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Michael Capecci

Written by

Freelance Developer from Chicago, IL. I am focusing on building cool stuff with Gatsby, WordPress and Shopify. Need help with a project? > michaelcapecci.com

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store