Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 14, 2022 12:28 am GMT

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 dateconst now = new Date();// Sun Nov 13 2022 18:28:22 GMT-0500 (Eastern Standard Time)

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 christmasconst christmas = new Date("Dec 25, 2022 00:00:00")

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() \\ 2022const month = christmas.getMonth()\\ 11 - Get month as a number (0-11)

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();

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 dayconsole.log(`${daysUntilChristmas} days!`) /// 41 days!

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!


Original Link: https://dev.to/spanglishgaby/how-to-use-the-javascript-date-object-to-count-days-until-a-specific-date-2bdo

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To