JavaScript – How to calculate the difference in days between two dates

I had a need to display a countdown until a certain event on a web site that used JavaScript and used the following code to perform the calculation.

Notes

  1. Use math.ceil if you want it to always round up, otherwise use math.round for it to round up or down

Code description

  1. Gets the current date and stores in the date variable
  2. Stores the date of the event you are counting down to in the event variable
  3. Sets the variable oneDay to be 1 day in milliseconds
  4. Subtracts the event’s date from the current date (in milliseconds)
  5. Divides the difference by 1 day to return the amount of days and then rounds up to the nearest day, storing in the daysLeft variable

Code

var date = new Date();
var event = new Date(2017, 2, 1);
var oneDay=1000*60*60*24;
var difference = event - date;
var daysLeft = Math.ceil(difference/oneDay);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s