solve negative values in a javascript based countdown - javascript

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 );

Related

how to know the result of substraction of date

I have a date like this 2017-07-25 09:30:49, when I subtract 2017-07-25 10:30:00 and 2017-07-25 09:30:00, I need a result like 1 Hours.
I can't find correct search key for googling what I need.
Anyone know what should I search on google ? or someone knows some function about that?
PS. Mysql or Javascript
Try with date object in javascript
Like this
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:49")
var diff = Math.abs(d1-d2); // difference in milliseconds
Then convert the milliseconds to hours
var hours = parseInt((diff/(1000*60*60))%24);
You can go through it
Get the time difference between two datetimes
But the query is not clear do you want only the hour difference or you want the difference converted to hour format
Like what it will give if 2017-07-25 09:30:49 and 2017-07-26 10:30:00 ? 25 hour or 1 hour?
here a code example of how to do it
var date1 = new Date("2017-07-25 09:30:49");
var date2 = new Date("2017-07-25 10:30:00");
var datesum = new Date(date1 - date2);
var hours = datesum.getHours();
var minutes = datesum.getMinutes();
var seconds = datesum.getSeconds();
console.log(hours + " hour, " + minutes + " minutes, " + seconds + " seconds" )
var dateString = "2017-07-25 09:30:49";
var dateString2= "2017-07-25 11:30:00";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateArray2= reggie.exec(dateString2);
var dateObject1= new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
var dateObject2= new Date(
(+dateArray2[1]),
(+dateArray2[2])-1, // Careful, month starts at 0!
(+dateArray2[3]),
(+dateArray2[4]),
(+dateArray2[5]),
(+dateArray2[6])
);
var diff = Math.abs(dateObject2-dateObject1); // difference in milliseconds
var hours = parseInt((diff/(1000*60*60))%24);
Try with the below dateFormatter function :
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:00")
var diff = Math.abs(d1-d2);
var d = dateFormatter(diff);
console.log(d);
function dateFormatter(t){
var cd = 24 * 60 * 60 * 1000;
var ch = 60 * 60 * 1000;
var cm = 60*1000;
var d = Math.floor(t / cd);
var h = '0' + Math.floor( (t - d * cd) / ch);
var m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
var s = '0' + Math.round((t - (d * cd) - (h * ch) - (m * cm))/1000);
return d + " days, " + h.substr(-2) + " hours, " + m.substr(-2) + " minutes, " +s.substr(-2)+ " seconds";
}

How to multiply a random time from milliseconds to minutes and seconds? [duplicate]

How to parse a given amount of milliseconds (e.g. 125230.41294642858) into a time format like: minutes:seconds?
var ms = 125230.41294642858,
min = 0|(ms/1000/60),
sec = 0|(ms/1000) % 60;
alert(min + ':' + sec);
Try the following
var num = Number(theTextValue);
var seconds = Math.floor(num / 1000);
var minutes = Math.floor(seconds / 60);
var seconds = seconds - (minutes * 60);
var format = minutes + ':' + seconds
Number.prototype.toTime = function(){
var self = this/1000;
var min = (self) << 0;
var sec = (self*60) % 60;
if (sec == 0) sec = '00';
return min + ':' + sec
};
var ms = (new Number('250')).toTime();
console.log(ms);
=> '0:15'
var ms = (new Number('10500')).toTime();
console.log(ms);
=> '10:30'
Even though moment.js does not provide such functionality, if you come here and you are already using moment.js, try this:
function getFormattedMs(ms) {
var duration = moment.duration(ms);
return moment.utc(duration.asMilliseconds()).format("mm:ss");
}
This workaround in moment was introduced in this Issue.

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 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))
}
}

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.

Jquery - Get the time in HH:MM format between two dates

I am getting the values from two text fields as date
var start_actual_time = $("#startPoint_complete_date").val();
var end_actual_time = $("#endPoint_complete_date").val();
which gives value
start_actual_time = 01/17/2012 11:20
end_actual_time = 01/18/2012 12:20
now i want to find out the duration in HH:MM format between these two dates (which is 25:00 in this case)
how can i do it...
var start_actual_time = "01/17/2012 11:20";
var end_actual_time = "01/18/2012 12:25";
start_actual_time = new Date(start_actual_time);
end_actual_time = new Date(end_actual_time);
var diff = end_actual_time - start_actual_time;
var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
alert(formatted);
See demo : http://jsfiddle.net/diode/nuv7t/5/ ( change mootools in jsfiddle
or open http://jsfiddle.net/nuv7t/564/ )
Working example:
gives alert message as 6:30
$(function(){
var startdate=new Date("01/17/2012 11:20");
var enddate=new Date("01/18/2012 12:20");
var diff = new Date(enddate - startdate);
alert(diff.getHours()+":"+diff.getMinutes());
});
First, I recommend this: http://www.mattkruse.com/javascript/date/ to convert the string to a date object, but you can convert it any way you want. Once converted, you can do this:
var difference_datetime = end_datetime.getTime() - start_datetime.getTime()
The getTime() function gets the number of milliseconds since 1970/01/01. Now you have the number of milliseconds of difference, and you can do whatever you want to convert to higher numbers (eg. divide by 1000 for seconds, divide that by 60 for minutes, divide that by 60 for hours, etc.)
I did something simular on a blog to see how long im together with my gf :P
http://daystogether.blogspot.com/ and this is how I did it:
// *****Set the unit values in milliseconds.*****
var msecPerMinute = 1000 * 60;
var msecPerHour = msecPerMinute * 60;
var msecPerDay = msecPerHour * 24;
// *****Setting dates*****
var today = new Date();
var startDate = new Date('10/27/2011 11:00:00');
// *****Calculate time elapsed, in MS*****
var interval = today.getTime() - startDate.getTime();
var days = Math.floor(interval / msecPerDay );
interval = interval - (days * msecPerDay );
var weeks = 0;
while(days >= 7)
{
days = days - 7;
weeks = weeks + 1;
}
var months = 0;
while(weeks >= 4)
{
weeks = weeks - 4;
months = months + 1;
}
// Calculate the hours, minutes, and seconds.
var hours = Math.floor(interval / msecPerHour );
interval = interval - (hours * msecPerHour );
var minutes = Math.floor(interval / msecPerMinute );
interval = interval - (minutes * msecPerMinute );
var seconds = Math.floor(interval / 1000 );
BTW this is just javascript, no jquery ;)
here you go:
function get_time_difference(start,end)
{
start = new Date(start);
end = new Date(end);
var diff = end.getTime() - start.getTime();
var time_difference = new Object();
time_difference.hours = Math.floor(diff/1000/60/60);
diff -= time_difference.hours*1000*60*60;
if(time_difference.hours < 10) time_difference.hours = "0" + time_difference.hours;
time_difference.minutes = Math.floor(diff/1000/60);
diff -= time_difference.minutes*1000*60;
if(time_difference.minutes < 10) time_difference.minutes = "0" + time_difference.minutes;
return time_difference;
}
var time_difference = get_time_difference("01/17/2012 11:20", "01/18/2012 12:20");
alert(time_difference.hours + ":" + time_difference.minutes);
start_date.setTime(Date.parse(start_actual_time));
end_date.setTime(Date.parse(end_actual_time));
//for check
start_date.toUTCString()
end_date.toUTCString()
/**
* Different in seconds
* #var diff int
*/
var diff = (end_date.getTime()-start_date.getTime())/1000;

Categories

Resources