Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How JavaScript assists in Leap Years Manipulations

In this article we will learn various aspects of handling leap years that could make a huge difference in the output if ignored.

The article will make the developers to learn how we can make use of JavaScript to incorporate some new functions that can be utilized with leap years.

Know our online course about javascript.

When we manipulate date intervals, one thing we cannot ignore is the inclusion of leap years. One needs to follow the proper process so as to calculate the difference between the articles of two dates. This way we will be able to calculate the leap years and handle the same appropriately.

Think of the situation where you are involved in calculating any sort of figures that involves annual data. Soon you will come to know that it can really make you land in some trouble to separate leap years from non-leap years.

How to identify the difference between leap and non-leap year?

The very first step that needs to be done being a developer is to identify if the provided date comprise of a leap year or not. The method listed below is incorporated to the Date's prototype object. This is done so as to apply directly to any Date object as in a Date.isLeapYear(). It accepts a Boolean that notifies it if we can make use of Universal time. There might be situation when you wouldn’t even think that there can be a date that can be affected by Universal time. However in case you get to some point where there this a time that is close enough for midnight for the time zone to shift the Universal time into the following year, at this point, the below method will return the correctly adjusted day.

Date.prototype.isLeapYear = function(utc) {
    var y = utc ? this.getUTCFullYear() : this.getFullYear();
    return !(y % 4) && (y % 100) || !(y % 400);
};

The expression given above manipulates if the given date falls in the scope of the leap year or not. It makes use of the subsequent Gregorian calendar rules:

  • Majority of the years that are divisible by 4 are Leap Years (i.e. 1992)
  • But, there are most of the years that are not divisible by 100 until and unless they are also divisible by 400. Here this will be considered as a leap year (i.e. 2000)

Working with the functions ignoring Leap Years

With the help of the below function, we will calculates the number of days between two dates when the extra leap days are ignored. This function is helpful when one requires dividing the total number of days by 365 so as to come to a yearly figure.

However, the point here to note is that, it is required to take the function into account in case the current year was a leap year and the two dates span the end of February. This is done by generating new dates making use of the non-leap year 2010. This is made use of to identify the number of day’s difference within the same year. Post this, the figure is added to 365 multiplied by number of year’s difference.

function daysBetweenExcludingLeapYears( date1, date2, utc ) {
    //2010 was NOT a leap year
    var cmpDate1 = new Date(2010, date1.getMonth(), date1.getDate());
    var cmpDate2 = new Date(2010, date2.getMonth(), date2.getDate());
    var date1Year = utc ? date1.getUTCFullYear() : date1.getFullYear();
    var date2Year = utc ? date2.getUTCFullYear() : date2.getFullYear();

    return Date.daysBetween(cmpDate1, cmpDate2) + (365 * (date1Year - date2Year));
}

The below function lists the static Date.daysBetween () function.

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;
    
  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

Working with Count of Only Leap Year Days between Two Dates

The function listed below count number of days between two dates that are part of leap years that will also come in handy to separate leap year days from non-leap year ones. This is done by breaking down the date range into three parts:

  • the partial first year days,
  • the full years and
  • the partial end year days.

The isLeapYear() function is utilized so as to judge if to count the days of that year or not.

We will again make use of the optional Universal time boolean argument. But, in this function the same has been made use of to set the year getter and setter to the correct function at the top of the function. This is for the reason that the getter is called lot number of times. We have a working date that is actually stored in a temporary (tmp) variable. This is done making use of the new Date (milliseconds) constructor so as to create a copy:

Date.leapYearDaysBetween = function(date1, date2, utc) {
    var count     = 0;
    var fnGetYear = utc ? getUTCFullYear : getFullYear;
    var fnSetYear = utc ? setUTCFullYear : setFullYear;
	
    if (d1.fnGetYear() == date2.fnGetYear() && date1.isLeapYear()) { 
        count = Date.daysBetween(date1,date2);
    } else {
      var lastDayInYear = new Date(date1.fnGetYear(), 11, 31);
      var tmp = new Date(date1.getTime()); //copy the date
      while (tmp.fnGetYear() < date2.fnGetYear()) {
          if (tmp.isLeapYear()) count += Date.daysBetween(tmp,lastDayInYear);

          tmp.fnSetYear(tmp.fnGetYear()+1);
      }
      if ( date2.isLeapYear() ) {
          var firstDayInYear = new Date(tmp.fnGetYear(), 0, 1);
          count += Date.daysBetween(firstDayInYear, date2);
      }
   }
   return count;
}

Surprised why we didn’t include an equivalent function for calculating non-leap year days? This is for the reason this can be established by subtracting the results of the Date.leapYearDaysBetween() function from those of Date.daysBetween().



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login