Javascript comparing two dates has wrong result - javascript

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 for me.
The minutes are not correct. If I refresh the browser, the seconds and minutes always start at 59. I think this may be because I am calling the Date object and possibly resetting it. What I am looking for is to count down to a certain date.
Because this is a learning experiment for me, if you see something else that may be improved upon, please let me know.
var dateA = new Date();
var dateB = new Date('June 3, 2014 00:27:00');
var cntr = setInterval(clock, 10);
function clock()
{
dateB = (dateB - 10);
var date = new Date(dateB);
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());
var secs = Math.ceil(date.getUTCSeconds() - dateA.getUTCSeconds() / 60);
var mill = Math.ceil(date.getUTCMilliseconds() - dateA.getUTCMilliseconds() / 999);
var str =
yrs + ' Years ' +
mos + ' Months ' +
days + ' Days ' +
hrs + ' Hours ' +
mins + ' Mins ' +
secs + ' Secs ' +
mill + ' Mill';
document.getElementById('clock').innerHTML = str;
}

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');
function clock() {
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;
}

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

try this..
function checkFromDate(sender, args) {
if (sender._selectedDate > new Date()) {
alert("You cannot select a day future than today.");
sender._selectedDate = new Date();
sender._textbox.set_Value(sender._selectedDate.format(sender._format))
}
}

Related

Difference between two dates by using angularjs?

This is my code
var departureDateFormat = new Date("10/09/15T09:25:00");
var arrivalDateFormat = new Date("13/09/15T13:25:00");
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[2];
var duration = moment.duration(arrivalDateFormat - departureDateFormat); //for reference of moment.js
var minutes = (duration / (1000 * 60)) % 60; // calliculating number of minutes
var hours = ((moment.duration(arrivalDateFormat - departureDateFormat)).humanize()); // calliculating number of hours
var timeInHours = ((hours == "an hour") ? 1 : hours.toString().substring(0, 1));
item.stopsDurationTime = timeInHours + "hrs " + minutes + "ms";
return timeInHours + "hrs " + minutes + "ms";
In the above code worked on IE , but it was not working on other browsers.Now i want to get difference between the above two dates by using angularJs/javascript.
You should use:
var minutes = duration.minutes();
var hours = duration.hours();
return hours + "hrs " + minutes + "ms";
Humanizing and then extracting the individual values is just unneeded overhead.
And moment can extract the hours and minutes for you so no need to compute from milliseconds.
Update:
Something like this:
var departureDate = moment("10/09/15T09:25:00", "DD/MM/YYYYTHH:mm:ss");
var arrivalDate = moment("13/09/15T13:35:10", "DD/MM/YYYYTHH:mm:ss");
var duration = moment.duration(arrivalDate.diff(departureDate));
var hours = Math.floor(duration.asHours());
var minutes = Math.floor(duration.asMinutes()-(hours*60));
return hours + "hrs " + minutes + "ms";
You have to define the format explicitly otherwise depending on your regional setting it will understand "10/09" as October, 9th or September, 10th.
Then you create a duration object. And you convert it to a number of hours (using "floor" to get a whole number). Then you convert it again to a number of minutes and subtract the hours you already got.

moment.js diff date formatting

I'm using moment.js and want to calculate the difference between two timestamp,format them afterwards and display them in a div.
var diffTime = moment(1390310146.791877).diff( 1390309386.271075);
This gives me 760 seconds, but I want to format it like this:
(days, hrs, mins, secs) and only show days, hours and seconds if they are higher than 0.
How do I achieve that ?
moment.duration should be used
let startTime = moment('09:45:20', 'h:mm:ss A').format("HH:mm:ss");
let endTime = moment('10:30:35', 'h:mm:ss A').format("HH:mm:ss")
var todayDate = moment(new Date()).format("MM-DD-YYYY"); //Can change, based on the requirement
var startDate = new Date(`${todayDate} ${startTime}`);
var endDate = new Date(`${todayDate} ${endTime}`);
var diffTime = moment(endDate).diff(startDate);
var duration = moment.duration(diffTime);
var years = duration.years(),
days = duration.days(),
months = duration.months(),
hrs = duration.hours(),
mins = duration.minutes(),
secs = duration.seconds();
var div = document.createElement('div');
div.innerHTML = years + ' years ' + months + 'months ' + days + ' days ' + hrs + ' hrs ' + mins + ' mins ' + secs + ' sec';
document.body.appendChild(div);
jsfiddle
try this
var diffTime = moment(moment(1390310146.791877).diff( 1390309386.271075)).format('H m s');
it will output "5 30 0"
Edit
here is the simple way to get the difference. for this both the time should be in the same timezone.
var a = moment(1390310146.791877);
var b = moment(1390309386.271075);
a.diff(b)//To get the difference in milliseconds
a.diff(b,'seconds')//To get the difference in seconds
a.diff(b,'minutes')//To get the difference in minutes
a.zone()//Get the timezone offset in minutes
hope this helps.

JavaScript date difference correction

I have a function that will calculate time between two date / time but I am having a small issue with the return.
Here is the way I collect the information.
Start Date
Start Time
Ending Date
Ending Time
Hours
And here is the function that calculates the dates and times:
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var sec = date2.getTime() - date1.getTime();
if (isNaN(sec)) {
alert("Input data is incorrect!");
return;
}
if (sec < 0) {
alert("The second date ocurred earlier than the first one!");
return;
}
var second = 1000,
minute = 60 * second,
hour = 60 * minute,
day = 24 * hour;
var hours = Math.floor(sec / hour);
sec -= hours * hour;
var minutes = Math.floor(sec / minute);
sec -= minutes * minute;
var seconds = Math.floor(sec / second);
var min = Math.floor((minutes * 100) / 60);
document.getElementById("result").value = hours + '.' + min;
}
If I put in todays date for both date fields and then 14:30 in the first time field and 15:35 in the second time field the result is shown as 1.8 and it should be 1.08
I didn't write this function but I am wondering if someone could tell me how to make that change?
Thank you.
If I understand correctly, the only issue you are having is that the minutes are not padded by zeroes. If this is the case, you can pad the value of min with zeroes using this little trick:
("00" + min).slice(-2)
I can't see why 15:35 - 14:30 = 1.08 is useful?
Try this instead:
function timediff( 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;
//take out milliseconds
difference_ms = difference_ms/1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var hours = Math.floor(difference_ms % 24);
var days = Math.floor(difference_ms/24);
return [days,hours,minutes,seconds];
}
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var diff = timediff(date1, date2);
document.getElementById("result").value = diff[1] + ':' + diff[2];
}
Verify if number of minutes is less than 10 and if it is then append an additional zero in front. Follow similar approach for seconds.

String to date conversion not working correctly in Javascript

I need to get time difference in this format: "HH:MM:SS" using a Javascript.
I have tried this:
var diff = Date.parse( time2) - Date.parse( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
and this:
var diff = new Date( time2) - new Date( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
These are the values of time2 and time1:
time1: "2012-11-07 15:20:32.161"
time2: "2012-11-07 17:55:41.451"
And result I am getting in both cases is:
total_time= 0.5250819444444444:31.504916666666666:1890.295
Which you can see is not correct
I think you are getting wrong diff value because of the millisecond part in the date delimited by .. Its not being accepted correctly by the data parser.
Try using the date and time part excluding the milliseconds as below:
var diff = Date.parse(time2.split(".")[0]) - Date.parse( time1.split(".")[0]);
Also while you are getting wrong difference diff, your time computation is also wrong.
It should be:
var second = Math.floor(diff /1000);
//convert the seconds into minutes and remainder is updated seconds value
var minute = Math.floor(second /60);
second = second % 60;
//convert the minutes into hours and remainder is updated minutes value
var hour = Math.floor(minute/60);
minute = minute %60;
var total_time= hour+":" minute+":"+second;
You forgot to remove the number of milliseconds you already calculated from diff. Here is a very verbose example on how you do it in a propper way.
var time1 = "2012-11-07 15:20:32.161",
time2 = "2012-11-07 17:55:41.451",
SECOND = 1000,
MINUTE = SECOND* 60,
HOUR = MINUTE* 60;
var diff = new Date(time2) - new Date(time1);
var hours = Math.floor(diff / HOUR); // Calculate how many times a full hour fits into diff
diff = diff - (hours * HOUR); // Remove hours from difference, we already caluclated those
var minutes = Math.floor(diff / MINUTE); // Calculate how many times a full minute fits into diff
diff = diff - (minutes * MINUTE); // Remove minutes from difference
var seconds = Math.floor(diff / SECOND); // As before
diff = diff - (seconds * SECOND);
var rest = diff;
var total_time = hours + ":" + minutes + ":" + seconds + " " + rest ;
DEMO

solve negative values in a javascript based countdown

I am creating a countdown to count the time between a match of the euro2012 that I intend to watch.
I've come with a working version of it but I don't understand why it gives me sometimes negative values.
I think it has to do with the way I wrote it, using the getTime() method.
Here is my code, could you guys help me find out to solve those negative values?
Thank you very much in advance.
<body onload="timeto2012()">
<script type="text/javascript">
function timeto2012() {
var euro2012 = new Date(2012, 5, 10, 20, 45);
var euro2012ms = euro2012.getTime();
var now = new Date();
var nowms = now.getTime();
var diff = euro2012ms - nowms;
var seconds = 1000;
var minutes = seconds*60;
var hours = minutes*60;
var days = hours*24;
var years = days*365;
var ddays = diff/days;
var dhours = (ddays - Math.round(ddays,1))*24;
var dminutes = (dhours - Math.round(dhours))*60;
var dseconds = (dminutes - Math.round(dminutes))*60;
document.getElementById("time").innerHTML='' + Math.round(ddays,1) +' days '+ Math.round(dhours,1) +' hours '+ Math.round(dminutes,1) +' minutes '+ Math.round(dseconds,1) + ' seconds remaining';
}
t=setInterval(timeto2012,500);
</script>
<div id="time"></div>
</body>
KOGI has the answer to your problem: You should use Math.floor instead of Math.round:
When there's x minutes and 30 - 59 seconds left, the (x - Math.round(x)) would be equivalent to (x - (x + 1)) after the rounding was done.
var ddays = diff/days;
var dhours = (ddays - Math.floor(ddays))*24;
var dminutes = (dhours - Math.floor(dhours))*60;
var dseconds = (dminutes - Math.floor(dminutes))*60;
Fiddle: http://jsfiddle.net/YHktx/3/
Here are some better calculations for you (derived from Aleksi Yrttiaho's jsFiddle)
var seconds = 1000;
var minutes = seconds*60;
var hours = minutes*60;
var days = hours*24;
var years = days*365;
var ddays = Math.floor( diff/days );
var dhours = Math.floor((diff % days) / hours );
var dminutes = Math.floor(((diff % days) % hours) / minutes );
var dseconds = Math.floor((((diff % days) % hours) % minutes) / seconds );

Categories

Resources