DEV Community

Cover image for How to use the Javascript Date Object to count days until a specific date
SpanglishGaby
SpanglishGaby

Posted on

How to use the Javascript Date Object to count days until a specific date

Finding out the number of days until a specific date sounds tricky, but using Javascript's built-in date object we can do it easily.

First, we need to understand what the Date object is, and how it works. At it's core, the date object contains a number which represents a specific instant in time, specifically, the number of seconds since January 1, 1970. By using a number of seconds to store the time, we can easily avoid problems related to day shifts caused by leap years and daylight savings time.

Making a new Date object

Getting today's date is easy. Simply use the Date object's constructor:

 // 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 make 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 the year, month, or day from the Date

Now that we have our time in a Date object, finding the Year, Month, or Day is as simple using Date's 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 Methods

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

Now that we know about Date's methods, getting 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 easily be converted to days until 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 there is a leap year! Using the same concepts explained above, you can calculate the number of days, hours, or even minutes until, or since any day or time of your choosing!

Top comments (0)