JavaScript: Working with Dates…

calendarWorking with Dates in computing can be quite tricky especially as we don’t always use the same date format around the globe.
For instance in the UK dates are represented using the following format: dd/mm/yyyy.

Let’s see how we could create a script to find out the number of days that have passed since the beginning of the year.
To do so we will need to:

  • Find out what today’s date is.
  • Extract the current year (of today’s date)
  • Create a new Date based on 01/01/ of the current year
  • Calculate the number of days between this date and today’s date
  • Display this number to the end user.

First we are going to use the Date() object in Javascript.

var today=new Date();

This line creates a new Date object and as we did not enter any parameters, it will use today’s date per default.

From this date we can extract the current year using the getYear() function as follows:

var currentYear=today.getFullYear();

Another way to create a Date object is to use the following code:

var oneDayInHistory=new Date(1969 , 7 , 21) //Create a new date for 21st of July 1969

So in our case we want the first day of the current year so we would use:

var beginningOfTheYear = new Date(currentYear, 1, 1) // (1, 1 stands of 1st of January)

Then we can calculate the difference between these two dates:

var dateDifference = today - beginningOfTheYear;

This code would return the number of milliseonds between these two days.
To get it in days we need to dive it by (1000*60*60*24) because there are 1000 milliseconds in 1 second, 60 seconds in one minute, 60 minutes in 1 hour and 24 hours in one day.
So:

dateDifference=dateDifference / (1000 * 60 *60 *24);

To get a whole number with no decimal we need to round this number:

dateDifference=Math.round(dateDifference);

We can then display the result back to the end user. So the full code will be as follows:

See the Pen waKmr by 101 Computing (@101Computing) on CodePen.

Your challenge:

Change this code to prompt the user to enter their Date of Birth. Get the code to calculate the number of days left till their next birthday.

Did you like this challenge?

Click on a star to rate it!

Average rating 4.7 / 5. Vote count: 3

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: