How to use Javascript Date object to count days till a specific date

It seems difficult to find out the number of days till a specific date, but we can do it easily using the built-in date object of JavaScript.

First, we need to understand what a Date object is and how it works. At its core, the Date object contains a number that represents a specific instant in time, specifically, the number of seconds since January 1, 1970. By using several seconds to store the time, we can easily avoid problems related to day shifts. Because of leap years and daylight saving time.

Getting today’s date is easy. Just use the constructor of the Date object:

 // Get today's date
const now = new Date();
// Sun Nov 13 2022 18:28:22 GMT-0500 (Eastern Standard Time)

enter fullscreen mode

exit fullscreen mode

To create a different date, for example, Christmas, you would use a different constructor, where the date is specified by a string:

// Make a date object for christmas
const christmas = new Date("Dec 25, 2022 00:00:00")
enter fullscreen mode

exit fullscreen mode

how to get year, month or day from date

Now that we have our time in a Date object, it’s as easy as finding the year, month, or day using the Date methods:

const year = christmas.getFullYear() \\ 2022
const month = christmas.getMonth()\\ 11 - Get month as a number (0-11)
enter fullscreen mode

exit fullscreen mode

other ways

  • getFullYear() Get the year as a four digit number (yyyy)
  • getMonth() Gets the month as a number (0-11)
  • getDate() Get the day as a number (1-31)
  • getDay() Gets the weekday as a number (0-6)
  • getHours() get hours (0-23)
  • getMinutes() get minutes (0-59)
  • getSeconds() get second (0-59)
  • getMilliseconds() get milliseconds (0-999)
  • getTime() Gets the time (milliseconds since January 1, 1970)

Now that we know about date methods, finding the difference in milliseconds between two dates is as easy as:

const msUntilChristmas = christmas.getTime() - now.getTime();
enter fullscreen mode

exit fullscreen mode

Which can be easily converted to the days leading up to Christmas by dividing by the number of ms per day:

const daysUntilChristmas = Math.floor(msUntilChristmas / (1000 * 60 * 60 * 24));
\\ use Math.floor() to round down
\\ 1000 ms per second
\\ 60 seconds per minute
\\ 60 minutes per hour
\\ 24 hours per day
console.log(`${daysUntilChristmas} days!`) /// 41 days!
enter fullscreen mode

exit fullscreen mode

Now you can calculate the exact number of days until Christmas, even if it is a leap year! Using the same concepts mentioned above, you can calculate the number of days, hours or minutes since any day or time of your choice!

Leave a Comment