Wednesday, October 19, 2011

Javascript - Parse Date, Get Difference

These functions will compute the difference of two given dates in Javascript.
For example:
var deadline = parseDate("2012-02-07");
var startdate = parseDate("2011-12-25");

var daysToFinish = daysDifference(deadline,startdate);
var weeksToFinish = weeksDifference(deadline,startdate);
var yearsToFinish = yearsDifference(deadline,startdate);

var daysToGo = daysFromNow(deadline);
var weeksToGo = weeksFromNow(deadline);
var yearsToGo = yearsFromNow(deadline);


  • parseDate(dateString) 
    • returns a date object based from string.

    • function parseDate(dateString){
      var dateParts = dateString.split('-');
      var yearIndex = 0;
      var monthIndex = 1;
      var dayIndex = 2;
      return new Date(dateParts[yearIndex], dateParts[monthIndex]-1, dateParts[dayIndex]);
      //or simply
      //return new Date(str);
      }
  • daysDifference(sourceDate, compareDate) 
    • returns the number of days difference with Date objects as parameters.

    • function daysDifference(sourceDate, compareDate){
      var oneDay = 1000*60*60*24;
      var daysDifference = (sourceDate-compareDate) / oneDay;
      return daysDifference.toFixed(2);
      }
  • weeksDifference(sourceDate, compareDate) 
    • returns the number of weeks difference with Date objects as parameters.

    • function weeksDifference(sourceDate, compareDate){
      var oneWeek = 1000*60*60*24*7;
      var weeksDifference = (sourceDate-compareDate) / oneWeek;
      return weeksDifference.toFixed(2);
      }
  • yearsDifference(sourceDate, compareDate) 
    • returns the number of years difference with Date objects as parameters.

    • function yearsDifference(sourceDate, compareDate){
      var oneYear = 1000*60*60*24*365.26; //approximate
      var yearsDifference = (sourceDate-compareDate) / oneYear;
      return yearsDifference.toFixed(2);
      }
  • daysFromNow(sourceDate) 
    • returns the number of days difference between a given date and the current date.

    • function daysFromNow(sourceDate){
      var currentDate = new Date();
      return daysDifference(sourceDate,currentDate);
      }
  • weeksFromNow(sourceDate) 
    • returns the number of weeks difference between a given date and the current date.

    • function weeksFromNow(sourceDate){
      var currentDate = new Date();
      return weeksDifference(sourceDate,currentDate);
      }
  • yearsFromNow(sourceDate) 
    • returns the number of years difference between a given date and the current date.

    • function yearsFromNow(sourceDate){
      var currentDate = new Date();
      return yearsDifference(sourceDate,currentDate);
      }


No comments:

Post a Comment