im having problem to calculate year month day in a same application but different page.
the 1st page display the date as 12Month(s) 5Day(s), while another page showing 1Year(s) 0Month(s) 1Day(s). how can this situation be explain?
<script type="text/javascript">
function myfunc(sDate1, sDate2) { //yyyy-MM-dd
var aDate, oDate1, oDate2, iDays;
aDate = sDate1.split('-');
oDate1 = new Date(aDate[0] + '-' + aDate[1] + '-' + aDate[2]);
aDate = sDate2.split("-");
oDate2 = new Date(aDate[0] + '-' + aDate[1] + '-' + aDate[2]);
iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24);
if (iDays <= 30) {
alert(iDays);
} else if (iDays > 30 && iDays <= 365) {
alert("Duration:" + parseInt((iDays / 30)) + "month(s) " + parseInt((iDays % 30)) + "day(s)")
} else {
alert("Duration:" + parseInt((iDays / 365)) + "year(s) " + parseInt(((iDays % 365) / 30)) + "month(s) " + parseInt(((iDays % 365) % 30)) + "day(s)");
}
return iDays;
}
</script>
My test code
Page1:
if (iDays <= 30)
$("#Display1").html(iDays + " day(s)");
else if (iDays > 30 && iDays <= 365)
$("#Display1").html(parseInt(iDays / 30) + " month(s) " + (iDays % 30) + " day(s)");
else if (iDays > 365)
$("#Display1").html(parseInt(iDays / 365) + " year(s) " + parseInt((iDays % 365) / 30) + " month(s) " + ((iDays % 365) % 30) + " day(s)");
Page2:
if (iDays <= 30)
$("#Display2").html(iDays + " day(s)");
else if (iDays > 30 && iDays <= 365)
$("#Display2").html(parseInt(iDays / 30) + " month(s) " + (iDays % 30) + " day(s)");
else if (iDays > 365)
$("#Display2").html(parseInt(iDays / 365) + " year(s) " + parseInt((iDays % 365) / 30) + " month(s) " + ((iDays % 365) % 30) + " day(s)");
Here is the code from the MSDN. I think the problem come from iDays
// Set the unit values in milliseconds.
var msecPerMinute = 1000 * 60;
var msecPerHour = msecPerMinute * 60;
var msecPerDay = msecPerHour * 24;
// Set a date and get the milliseconds
var date = new Date('6/15/1990');
var dateMsec = date.getTime();
// Set the date to January 1, at midnight, of the specified year.
date.setMonth(0);
date.setDate(1);
date.setHours(0, 0, 0, 0);
// Get the difference in milliseconds.
var interval = dateMsec - date.getTime();
// Calculate how many days the interval contains. Subtract that
// many days from the interval to determine the remainder.
var days = Math.floor(interval / msecPerDay );
interval = interval - (days * msecPerDay );
// 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 );
// Display the result.
document.write(days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds.");
//Output: 164 days, 23 hours, 0 minutes, 0 seconds.
Try to calculate it with this method for the days
This will look like this
<script type="text/javascript">
function myfunc(sDate1, sDate2) { //yyyy-MM-dd
var aDate, oDate1, oDate2, iDays;
// Set the unit values in milliseconds.
var msecPerMinute = 1000 * 60;
var msecPerHour = msecPerMinute * 60;
var msecPerDay = msecPerHour * 24;
aDate = sDate1.split('-');
oDate1 = new Date(aDate[0] + '-' + aDate[1] + '-' + aDate[2]);
aDate = sDate2.split("-");
oDate2 = new Date(aDate[0] + '-' + aDate[1] + '-' + aDate[2]);
var interval = oDate2.getTime() - oDate1.getTime();
iDays = Math.floor(interval / msecPerDay );
if(iDays <=30){
alert(oDate1);
}else if(iDays>30 && iDays <=365){
alert("Duration:" + parseInt((iDays/30)) + "month(s) " + parseInt((iDays%30)) + "day(s)")
}else{
alert("Duration:" + parseInt((iDays/365)) + "year(s) " + parseInt(((iDays%365)/30)) + "month(s) " + parseInt(((iDays%365)%30)) + "day(s)");
}
return iDays;
}
Related
I have jQuery function timer.
(function( $ ){
$.fn.makeTimer = function(val){
var val = val;
setInterval(function() {
var result;
var startTime = new Date(val);
startTime = (Date.parse(startTime) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var timePassed = now - startTime;
var years = Math.floor(timePassed / (86400 * 365));
var months = Math.floor((timePassed / (86400 * 30.41)) - (years * 12));
var days = Math.floor((timePassed / 86400) - (years * 365) - (months * 30.41));
var hours = Math.floor( (timePassed / 3600 ) - (years * (24 * 365)) - (months * (24 * 30.41)) - (days * 24) ) ;
var minutes = Math.floor( (timePassed / 60) - ( years * (1440 * 365) ) - (months * (1440 * 30.41)) - (days * (60 * 24)) - (hours * 60 ) );
var seconds = Math.floor(timePassed - (years * (86400 * 365)) - (months * (86400 * 30.41)) - (days * 86400) - (hours * 3600) - (minutes * 60) );
if (months < "10") { months = "0" + months; }
if (days < "10") { days = "0" + days; }
if (hours < "10") { hours = "0" + hours; }
if (minutes < "10") { minutes = "0" + minutes; }
if (seconds < "10") { seconds = "0" + seconds; }
console.log(hours + ":" + minutes + ":" + seconds);
result = hours + ":" + minutes + ":" + seconds;
return result;
}, 1000);
};
})( jQuery );
$("#timers").makeTimer("07 April 2022 13:00:00 GMT+07:00");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timers"></div>
And I call like this,
$("#timers").makeTimer("07 April 2022 13:00:00 GMT+07:00");
This is the HTML element,
<div id="timers"></div>
After tried to run the code, I can't print/echo the text into $("#timers"), but when I try to console.log(hours + ":" + minutes + ":" + seconds); I can see the value.
What I want, how to return result correctly into this element?
Add at the top of your function:
var $element = this;
Then, after calculating results:
$element.text(result)
If you need all the values:
$element.append(`<br />${result}`)
(function( $ ){
$.fn.makeTimer = function(val){
var val = val;
var $element = this;
setInterval(function() {
var result;
var startTime = new Date(val);
startTime = (Date.parse(startTime) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var timePassed = now - startTime;
var years = Math.floor(timePassed / (86400 * 365));
var months = Math.floor((timePassed / (86400 * 30.41)) - (years * 12));
var days = Math.floor((timePassed / 86400) - (years * 365) - (months * 30.41));
var hours = Math.floor( (timePassed / 3600 ) - (years * (24 * 365)) - (months * (24 * 30.41)) - (days * 24) ) ;
var minutes = Math.floor( (timePassed / 60) - ( years * (1440 * 365) ) - (months * (1440 * 30.41)) - (days * (60 * 24)) - (hours * 60 ) );
var seconds = Math.floor(timePassed - (years * (86400 * 365)) - (months * (86400 * 30.41)) - (days * 86400) - (hours * 3600) - (minutes * 60) );
if (months < "10") { months = "0" + months; }
if (days < "10") { days = "0" + days; }
if (hours < "10") { hours = "0" + hours; }
if (minutes < "10") { minutes = "0" + minutes; }
if (seconds < "10") { seconds = "0" + seconds; }
console.log(hours + ":" + minutes + ":" + seconds);
result = hours + ":" + minutes + ":" + seconds;
$element.text(result);
return result;
}, 1000);
};
})( jQuery );
$("#timers").makeTimer("07 April 2022 13:00:00 GMT+07:00");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timers"></div>
I'm having an issue making this countdown, it shows more hours than "23". Any idea how to fix it?
String.prototype.toHHMMSS = function() {
var sec_num = parseInt(this, 10);
var days = Math.floor(sec_num / 86400);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
return days + " days" + " : " + hours + " hrs" + " : " + minutes + " min" + " : " + seconds + " sec";
};
let startTime = 1649303300; // database unix-timestamp value
setInterval(() => {
let curTime = (new Date()).getTime() / 1000;
curTime = parseInt(curTime);
if (curTime < startTime){
document.getElementById("timer1").innerText = ("LAUNCHING IN:");
document.getElementById("timer").innerText = (`${startTime-curTime}`).toHHMMSS();
}
else {
document.getElementById("timer1").innerText = ("LAUNCHED");
document.getElementById("timer").innerText = ("");
}
}, 1000);
"
I'm getting more than "23" for the "hours" variable instead of increasing the days every 24 hours.
You're not subtracting the days from the hours variable in the way that you're doing it for minutes and seconds. Try declaring your hours variable like this:
var days = Math.floor(sec_num / 86400);
var hours = Math.floor((sec_num - (days * 86400)) / 3600);
You can also use modular arithmetic to strip the excess values. You can use the modulo operator for this, e.g.
String.prototype.toHHMMSS = function() {
var sec_num = parseInt(this, 10);
var days = Math.floor(sec_num / 86400);
var hours = Math.floor(sec_num / 3600) % 24;
var minutes = Math.floor(sec_num / 60) % 60;
var seconds = sec_num % 60;
return days + " days" + " : " + hours + " hrs" + " : " + minutes + " min" + " : " + seconds + " sec";
};
I have this function that converts minutes into an hour / minute format:
return Math.floor(diffMins / 60) + " Hour " + diffMins % 60 + " Minutes.";
What I would like to do is to make it so that if there are no hours then the "0 hours" does not show. Can anyone recommend a good way that I can do this?
Floor; check if more than 0 hours; if not, output empty string; otherwise check if one hour, if yes, output "1 hour", if not, output number of hours + "hours"
var h = Math.floor(diffMins / 60);
var hours = (h > 0 ? (h==1 ? "1 hour" : h+" hours") : "");
var mins = diffMins % 60;
return hours + mins > 1 ? mins + " minutes." : " 1 minute." ;
This would work..
return (diffMins>60?Math.floor(diffMins / 60) + " Hour ":"") + diffMins % 60 + " Minutes."
return Math.floor(diffMins / 60) ==0 ? diffMins % 60 + " Minutes." : Math.floor(diffMins / 60) + " Hour " + diffMins % 60 + " Minutes."
function makePlural(count, words) {
if (count == 0 || count > 1)
return count + " " + words[1];
return count + " " + words[0];
}
function minutesToString(diffMins) {
var hours = Math.floor(diffMins / 60);
var minutes = diffMins % 60;
var hoursStr = (hours == 0) ? "" : (makePlural(hours, ["Hour", "Hours"]) + " ");
var minutesStr = makePlural(minutes, ["minute", "minutes"]);
return hoursStr + minutesStr;
}
function yourFunction(diffMins) {
if (minutes < 60) {
return minutes + " Minutes.";
}
return Math.floor(minutes / 60) + " Hour " + minutes % 60 + " Minutes.";
}
I am making a comments system for my site and want to have the time since posted update at a set interval. Currently my javascript only takes into account one data-time attribute for every class but I want it to use each classes data-time attribute.
My html looks something a little like this
<div class="commentTime noSelect" data-time="1424867042">0 days and 0 hours and 5 minutes and 40 seconds</div>
<div class="commentTime noSelect" data-time="1424863061">0 days and 0 hours and 5 minutes and 40 seconds</div>
<div class="commentTime noSelect" data-time="1424861992">0 days and 0 hours and 5 minutes and 40 seconds</div>
etc...
data-time is the time in seconds since 1970. Now here's my javascript.
//Time Update Function
function time_elapsed() {
time = $(".commentTime").attr("data-time");
currentTime = new Date().getTime() / 1000;
time = currentTime - time;
var days = Math.floor(time / 86400);
var hours = Math.floor((time - (days * 86400 ))/3600);
var minutes = Math.floor((time - (days * 86400 ) - (hours *3600 ))/60);
var seconds = Math.floor((time - (days * 86400 ) - (hours *3600 ) - (minutes*60)));
if ( seconds > 1 ){ updatedTime = seconds + " seconds"; }else{ updatedTime = seconds + " second"; }
if ( minutes > 1 ){ updatedTime = minutes + " minutes and " + updatedTime; }else{ updatedTime = minutes + " minute and " + updatedTime; }
if ( minutes > 1 ){ updatedTime = hours + " hours and " + updatedTime; }else{ updatedTime = hours + " hour and " + updatedTime; }
if ( minutes > 1 ){ updatedTime = days + " days and " + updatedTime; }else{ updatedTime = days + " day and " + updatedTime; }
$(".commentTime").html(updatedTime);
}
setInterval(time_elapsed(),1000);
I'm pretty new to javascript and I just can't seem to make it treat each div uniquely.
Try something like that, see also Fiddle http://jsfiddle.net/ApfJz/37/:
function time_elapsed() {
$(".commentTime").each(function(){
var time = $(this).attr("data-time");
var currentTime = new Date().getTime() / 1000;
var updatedTime;
time = currentTime - time;
var days = Math.floor(time / 86400);
var hours = Math.floor((time - (days * 86400 ))/3600);
var minutes = Math.floor((time - (days * 86400 ) - (hours *3600 ))/60);
var seconds = Math.floor((time - (days * 86400 ) - (hours *3600 ) - (minutes*60)));
if ( seconds > 1 ){ updatedTime = seconds + " seconds"; }else{ updatedTime = seconds + " second"; }
if ( minutes > 1 ){ updatedTime = minutes + " minutes and " + updatedTime; }else{ updatedTime = minutes + " minute and " + updatedTime; }
if ( minutes > 1 ){ updatedTime = hours + " hours and " + updatedTime; }else{ updatedTime = hours + " hour and " + updatedTime; }
if ( minutes > 1 ){ updatedTime = days + " days and " + updatedTime; }else{ updatedTime = days + " day and " + updatedTime; }
$(this).html(updatedTime);
});
}
setInterval(time_elapsed,1000);
What you are doing is when you select the time it takes it from $(".commentTime"); which select more than one element. You have to select them all and loop through - treating each one individually. This could be tidied up further but I think this should work:
function time_elapsed() {
$(".commentTime").each(function(){
time = $(this).attr("data-time");
currentTime = new Date().getTime() / 1000;
time = currentTime - time;
var days = Math.floor(time / 86400);
var hours = Math.floor((time - (days * 86400 ))/3600);
var minutes = Math.floor((time - (days * 86400 ) - (hours *3600 ))/60);
var seconds = Math.floor((time - (days * 86400 ) - (hours *3600 ) - (minutes*60)));
updatedTime = seconds + " second" + (seconds == 1 ? "" : "s");
updatedTime = minutes + " minute" + (minutes == 1 ? "" : "s") + " and " + updatedTime;
updatedTime = hours + " hour" + (hours == 1 ? "" : "s") + " and " + updatedTime;
updatedTime = days + " day" + (days == 1 ? "" : "s") + " and " + updatedTime;
$(this).html(updatedTime);
});
}
setInterval(time_elapsed,1000);
My code is located below. I'm trying to set a countdown, however I can't figure out how to set the timer to operate. I've tried changing the "var setting". When I do it seems that the countdown works, however it glitches and the numbers appear but all go back to "0". Really confused. Someone Please help!
(function($) {
$.fn.countdown = function(options) {
var settings = { 'date': "30 september 2014 16:24:00" };
if(options) {
$.extend(settings, options);
}
this_sel = $(this);
function count_exec() {
eventDate = Date.parse(settings['date']) / 1000; // Parse the date string
currentDate = Math.floor($.now() / 1000); // Find the timestamp for now
seconds = eventDate - currentDate; // Find the number of seconds remaining
if (seconds <= 0) { // After the event date has passed
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
} else {
days = Math.floor(seconds / (60 * 60 * 24)); // Divide to find the number of days remaining
seconds -= days * 60 * 60 * 24; // Subtract the number of (complete, => 24 hours) days calculated above
hours = Math.floor(seconds / (60 * 60)); // Get the number of hours from that modified number ^
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
}
this_sel.find('#days').val(days).trigger('change');
this_sel.find('#hours').val(hours).trigger('change');
this_sel.find('#mins').val(minutes).trigger('change');
this_sel.find('#secs').val(seconds).trigger('change');
} // End of count_exec();
count_exec();
interval = setInterval(count_exec, 1000);
} // End of the main function
}) (jQuery);
Please but below code in your file and apply the desire date. It works fine for me. Let me know if any issue.
<body>
<form name="count">
<input type="text" size="69" name="count2">
</form>
<script type="text/javascript">
//change the text below to reflect your own,
var before = "Christmas!"
var current = "Today is Christmas. Merry Christmas!"
var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
function countdown(yr, m, d) {
theyear = yr; themonth = m; theday = d
var today = new Date()
var todayy = today.getYear()
if (todayy < 1000)
todayy += 1900
var todaym = today.getMonth()
var todayd = today.getDate()
var todayh = today.getHours()
var todaymin = today.getMinutes()
var todaysec = today.getSeconds()
var todaystring = montharray[todaym] + " " + todayd + ", " + todayy + " " + todayh + ":" + todaymin + ":" + todaysec
futurestring = montharray[m - 1] + " " + d + ", " + yr
dd = Date.parse(futurestring) - Date.parse(todaystring)
dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1)
dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1)
dmin = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1)
dsec = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1)
if (dday == 0 && dhour == 0 && dmin == 0 && dsec == 1) {
document.forms.count.count2.value = current
return
}
else
document.forms.count.count2.value = "Only " + dday + " days, " + dhour + " hours, " + dmin + " minutes, and " + dsec + " seconds left until " + before
setTimeout("countdown(theyear,themonth,theday)", 1000)
}
//enter the Future count down date using the format year/month/day
countdown(2016, 9, 24)
</script>
</body>