How To Calculate Time For Javascript Functions

25 Jun 2020 - Andrew McCall

a clock being held in the air

As I’ve been learning more javascript I found dates and time to be a bit confusing. I will try and break down some of the parts to make it easier for someone else to learn as well.

The Date Object

Let us say you wanted to work with the date January 1st, 2021. In javascript we could write something like this:

let newYear = newDate(2021, 00, 01)

that would return:

Date Fri Jan 01 2021 00:00:00 GMT-0500 (Eastern Standard Time)

So the use case that I needed was pretty simple but hard for me to figure out at first so I want to go over it for future reference.

We all build a new year countdown clock at some point when learning dates and times. The one I ended up referencing was Brad Traversy’s which you can find here.

To make a countdown timer you only need the current time and the date you want to count down to. to achieve this I did this:

Javascript Time Code Snippets

const currentYear = new Date().getFullYear();
const newYear = new Date(`January 01 ${currentYear + 1} 00:00:00`); //  this allows it to update every year
const currentTime = new Date();
const diff = newYear - currentTime;

This is pretty much the set up in the function.

diff returns a value like:

newYear - new Date()

Javascript likes to work in milliseconds so I need to convert those values.

to do that here are the following javascript time forumulas I used:

let d = Math.round(diff / 1000 / 60 / 60 / 24);
  let h = Math.round((diff / 1000 / 60 / 60) % 24);
  let m = Math.round((diff / 1000 / 60) % 60);
  let s = Math.round((diff / 1000) % 60);

These are just simple math formulas that you can find anywhere on the internet. basically you just need to update your dom elements if you are creating a counter.

now if you want to have it update every second you just need to add the following line of code:

setInterval(updateTime, 1000);

This will start executing updateTime function every 1000 ms.

I hope this helps someone when they go to work with converting days, minutes, hours, etc. If you have any questions or want to see some code feel free to reach out to me here!

chevron_left Recursive Functions
How To Initialize A Javascript XMLHttpRequest chevron_right
Tags: javascript, web development