Skip to content Skip to sidebar Skip to footer

Javascript Comparing Two Dates Has Wrong Result

I'm trying to learn a little more about JavaScript and decided to make a countdown timer that will show from years all the way down to milliseconds. It's just a learning experiment

Solution 1:

var yrs  = Math.abs(date.getUTCFullYear() - dateA.getUTCFullYear() );
var mos  = Math.abs(date.getUTCMonth() - dateA.getUTCMonth());
var days = Math.abs(date.getUTCDate() - dateA.getUTCDate());
var hrs  = Math.abs(date.getUTCHours() - dateA.getUTCHours());
var mins = Math.abs(date.getUTCMinutes() - dateA.getUTCMinutes());

You cannot just take the absolute value of the differences of each part of the date! You end up with totally wrong numbers.

var secs = Math.ceil(date.getUTCSeconds() - dateA.getUTCSeconds() / 60);
var mill = Math.ceil(date.getUTCMilliseconds() - dateA.getUTCMilliseconds() / 999);

Why would you divide these by 60 and by nearly-1000?!

Instead, to calculate the time difference, you will need to get the complete difference (in milliseconds, usually) and convert that into the different units. Your function should look like this:

var el = document.getElementById('clock');
functionclock() {
  var diff = dateB - Date.now();
  var yrs  = Math.floor(diff / 31536000000);
  var mos  = Math.floor(diff / 2678400000) % 12;
  var days = Math.floor(diff / 86400000)   % 31;
  var hrs  = Math.floor(diff / 3600000)    % 24;
  var mins = Math.floor(diff / 60000)      % 60;
  var secs = Math.floor(diff / 1000)       % 60;
  var mill =            diff               % 1000;
  var str  =
    yrs  + ' Years   '  +
    mos  + ' Months   ' +
    days + ' Days   '   +
    hrs  + ' Hours   '  +
    mins + ' Mins   '   +
    secs + ' Secs   '   +
    mill + ' Mill';
  el.innerText = str;
}

Solution 2:

If you're using javascript for comparing dates or counting number of days, you might have some problems. You should use a library for better results.

I recommend you to use http://momentjs.com/ for date or time function. It's easy to use and much more flexible.

This should answer your question: Countdown timer using Moment js

Solution 3:

trythis..

functioncheckFromDate(sender, args) {
    if (sender._selectedDate > newDate()) {
        alert("You cannot select a day future than today.");
        sender._selectedDate = newDate();
        sender._textbox.set_Value(sender._selectedDate.format(sender._format))
    }
}

Post a Comment for "Javascript Comparing Two Dates Has Wrong Result"