Building a custom date display from Scratch (Part 1)

JavaScript Date Object (true story)

Popular question…

Thank you for reading! Comment, share and turn on the notification icon for more!

Wait, obviously we’re still not there yet!

Date objects have access to several methods available to obtain a date in various formats. At first glance, the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC isn't all that useful in creating a date display. However, it is important to note that most of the functions output the date and time in Coordinated Universal Time (UTC), whereas the user's device provides the local time. Which brings us to the question...

How to build a custom date display?

First, let’s get something straight. Most tutorials out there are way overthinking how to do this. Today, as part of this series, we are going to take the first step and build a simple but code-effective time display to understand the building blocks and fundamentals of the JavaScript Date object.

Step 1: Setting criteria

Calling gives us the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. However, to get a running time display (as a normal clock would work) we need to be able to do and establish the following criteria: i) how are we formatting to get human-readable data and ii) how often are we updating our time display.

Step 2: Formatting

Even though the Date object has several methods available to accomplish this task, we will opt to use JavaScript's Intl object which also happens to provide standardised language-sensitive date and time formatting. Let's take a look how does it format our current milliseconds logging to the console its result.

Step 3: Updating the time

There is really no single approach on how to update the time. Among the popular options: setInterval() and setTimeout(), I'd recommend using the former rather than the latter due to their recursive timeouts. The difference may seem insignificant, but setInterval() includes the time taken to execute the code you want to run, as opposed to setTimeout() which does the exact opposite.

  • setInterval() — would execute your code every 1000 milliseconds
  • setTimeout() — would execute your code every 950 milliseconds

Final thoughts

Play with it. Feel free to use several different option parameters in Intl.DateTimeFormat() to display the date and time in any way you need. Also keep in mind that code shown above runs in the console, if you replace the timeGenerator function's console.log for return you can pass the data to a DOM object by selecting the node in the timeDisplay IIFE. Here's what that would look like:



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