i have the following function:
function update_comments(){
$('.comment_list_item').each(function(){
var current_comment = $(this).find('.comment_time');
var old_text = current_comment.text();
var current_time = new Date().getTime();
var timer = $(this).find('.hour_glass')
var old_time = parseFloat(timer.val());
var new_time = current_time - old_time;
var minutes=1000*60;
var hours=minutes*60;
var days=hours*24;
var new_text = '';
if(days > 0){
new_text = days+' Days ago';
}else if(hours > 0){
if(hours === 1){
new_text = hours+' Hour ago';
}else{
new_text = hours+' Hours ago';
}
}else{
if(minutes === 1){
new_text = minutes+' Minute ago';
}else{
new_text = minutes+' Minutes ago';
}
}
current_comment.text(new_text);
});
}
Where old_time is an input field with the value microtime(true);
Now after 1 minute the result is 86400000 days can anyone tell me why?
Did you read your code carefully? It includes the following lines:
var minutes=1000*60;
var hours=minutes*60;
var days=hours*24;
So yes, you are computing minutes, hours, days based on a constant (not the difference between old time and new time). Specifically, from the above it follows that
days = 1000 * 60 * 60 * 24 = 86400000
just as you observed.
The following:
var minutes = milliseconds / (1000 * 60);
var hours = minutes / 60;
var days = hours / 24;
is the more conventional approach for converting milliseconds into minutes into hours into days...
Assuming new_time is in milliseconds (very probably), You should have:
var minutes = new_time / 1000 / 60;
var hours= minutes / 60;
var days = hours / 24;
Cheers
Related
My countdown shows the wrong hours with my current location. It shows 6 hours difference from my time zone. My time zone is Asia/Dhaka.
How do I get the correct hours? days, Minutes, and Seconds are correct. Only problem with hours.
// Got this function from thisinterestsme
function calculateChristmasCountdown() {
//Get today's date.
var now = new Date();
//Get the current month. Add a +1 because
//getMonth starts at 0 for January.
var currentMonth = (now.getMonth() + 1);
//Get the current day of the month.
var currentDay = now.getDate();
//Work out the year that the next Christmas
//day will occur on.
var nextChristmasYear = now.getFullYear();
if (currentMonth == 12 && currentDay > 25) {
//This year's Christmas Day has already passed.
nextChristmasYear = nextChristmasYear + 1;
}
var nextChristmasDate = nextChristmasYear + '-12-25T00:00:00.000Z';
var christmasDay = new Date(nextChristmasDate);
//Get the difference in seconds between the two days.
var diffSeconds = Math.floor((christmasDay.getTime() - now.getTime()) / 1000);
var days = 0;
var hours = 0;
var minutes = 0;
var seconds = 0;
//Don't calculate the time left if it is Christmas day.
if (currentMonth != 12 || (currentMonth == 12 && currentDay != 25)) {
//Convert these seconds into days, hours, minutes, seconds.
days = Math.floor(diffSeconds / (3600 * 24));
diffSeconds -= days * 3600 * 24;
hours = Math.floor(diffSeconds / 3600);
diffSeconds -= hours * 3600;
minutes = Math.floor(diffSeconds / 60);
diffSeconds -= minutes * 60;
seconds = diffSeconds;
}
//Add our counts to their corresponding HTML elements.
document.getElementById('cws_xmas_days').innerHTML = days;
document.getElementById('cws_xmas_hours').innerHTML = hours;
document.getElementById('cws_xmas_minutes').innerHTML = minutes;
document.getElementById('cws_xmas_seconds').innerHTML = seconds;
setTimeout(calculateChristmasCountdown, 1000);
}
calculateChristmasCountdown();
<span id="cws_xmas_days"></span> days
<span id="cws_xmas_hours"></span> hours
<span id="cws_xmas_minutes"></span> minutes
<span id="cws_xmas_seconds"></span> seconds
You have used the Z timezone specifier in the parsed date which means that you're counting down to 25th December using the UTC/GMT timezone. Try removing the Z to get the local equivalent.
// Got this function from thisinterestsme
function calculateChristmasCountdown() {
//Get today's date.
var now = new Date();
//Get the current month. Add a +1 because
//getMonth starts at 0 for January.
var currentMonth = (now.getMonth() + 1);
//Get the current day of the month.
var currentDay = now.getDate();
//Work out the year that the next Christmas
//day will occur on.
var nextChristmasYear = now.getFullYear();
if (currentMonth == 12 && currentDay > 25) {
//This year's Christmas Day has already passed.
nextChristmasYear = nextChristmasYear + 1;
}
var nextChristmasDate = nextChristmasYear + '-12-25T00:00:00.000';
var christmasDay = new Date(nextChristmasDate);
//Get the difference in seconds between the two days.
var diffSeconds = Math.floor((christmasDay.getTime() - now.getTime()) / 1000);
var days = 0;
var hours = 0;
var minutes = 0;
var seconds = 0;
//Don't calculate the time left if it is Christmas day.
if (currentMonth != 12 || (currentMonth == 12 && currentDay != 25)) {
//Convert these seconds into days, hours, minutes, seconds.
days = Math.floor(diffSeconds / (3600 * 24));
diffSeconds -= days * 3600 * 24;
hours = Math.floor(diffSeconds / 3600);
diffSeconds -= hours * 3600;
minutes = Math.floor(diffSeconds / 60);
diffSeconds -= minutes * 60;
seconds = diffSeconds;
}
//Add our counts to their corresponding HTML elements.
document.getElementById('cws_xmas_days').innerHTML = days;
document.getElementById('cws_xmas_hours').innerHTML = hours;
document.getElementById('cws_xmas_minutes').innerHTML = minutes;
document.getElementById('cws_xmas_seconds').innerHTML = seconds;
setTimeout(calculateChristmasCountdown, 1000);
}
calculateChristmasCountdown();
<span id="cws_xmas_days"></span> days
<span id="cws_xmas_hours"></span> hours
<span id="cws_xmas_minutes"></span> minutes
<span id="cws_xmas_seconds"></span> seconds
Hi everybody I’ve tried (and failed) to change this simple jquery code to countdown 24 hours instead of the current 1 hour. I have a function called getMinutesUntilNextHour() that should calculate and display the 24 hour countdown:
function getMinutesUntilNextHour() {
var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();
var cur_mins = 60 - mins;
var cur_secs = 60 - secs;
if (cur_secs == 60) {
cur_mins = cur_mins;
cur_secs = 0;
} else {
cur_mins = cur_mins - 1;
}
if(secs > 50){
var response = (cur_mins) + ":0" + (cur_secs);
} else if(cur_secs == 0) {
var response = (cur_mins) + ":00";
} else {
var response = (cur_mins) + ":" + (cur_secs);
}
jQuery('#time_till_hour').text(function(){
return response;
});
setTimeout(getMinutesUntilNextHour, 1000);
}
getMinutesUntilNextHour();
I added now.getHours() then cur_hours = 24 - hours but it doesn’t display correctly. Should I add something to if current hours = 0 section?
Thanks in advance for any help you may be able to offer
Perhaps you could adjust and simplify your getMinutesUntilNextHour() function in the following way:
function getMinutesUntilNextHour() {
var now = new Date();
var hours = now.getHours();
var mins = now.getMinutes();
var secs = now.getSeconds();
// Compute time remaining per unit
var cur_hours = 23 - hours;
var cur_mins = 60 - mins;
var cur_secs = 60 - secs;
// Correct zero padding of hours if needed
if(cur_hours < 10) {
cur_hours = '0' + cur_hours;
}
// Correct zero padding of minutes if needed
if(cur_mins < 10) {
cur_mins = '0' + cur_mins;
}
// Correct zero padding of seconds if needed
if(cur_secs < 10) {
cur_secs = '0' + cur_secs;
}
// Format the countdown string
var response = cur_hours + ':' + cur_mins + ':' + cur_secs;
jQuery('#time_till_hour').text(response);
setTimeout(getMinutesUntilNextHour, 1000);
}
getMinutesUntilNextHour();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="time_till_hour">
</div>
Hope that helps!
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates
for example ,
startdatetime = "09-06-2017 10:30"
enddatetime = "10-06-2017 11:45"
i need this result : 1 day 1 hour and 15 minutes
I try this one
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
console.log(a);
var hours = Math.trunc(a/60);
var minutes = a % 60;
var one_day=1000*60*60*24
var days = Math.ceil(a/one_day)
var time = [hours,minutes,days];
return time;
}
i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance
Using momentjs, you can :
Parse your input string using moment(String, String)
Parse your input string using moment.utc
Get difference using diff() function
Create a duration from the difference value
Use duration days(), hours(), minutes() to get your result
Here a live sample:
var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.days() + ' days ' + dur.hours() + ' hour ' + dur.minutes() + ' minutes');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
If you want you can use moment-duration-format plug-in to get the same result using format() method on duration. Here a working sample:
var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.format('d [day] h [hour] m [minutes]'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
Well, if you look at documentation for javascript Date objects, there is a getTime() method . You can also use the valueOf() method. They both return the number of milliseconds representing your Date object.
You can simply call that on both Date objects and then find the difference. Once you have the difference you can find the amount of secs, mins , hrs, days, etc. Here is an example:
var start = new Date(*some date*);
var end = new Date(*some date*);
var dif = end.valueOf() - start.valueOf();
if (dif >= 0) {
var secs = Math.floor(dif / 1000 % 60);
var mins = Math.floor(dif / 1000 / 60 % 60);
var hrs = Math.floor(dif / 1000 / 60 / 60 % 24);
var days =
Math.floor(dif / 1000 / 60 / 60 / 24 % 365);
var yrs =
Math.floor(dif / 1000 / 60 / 60 / 24 / 365);
Try the following:
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(minutes)
{
var hours = (minutes / 60 | 0) % 24;
var minutes = (minutes | 0) % 60;
var days = minutes / 60 / 24 | 0;
return [hours, minutes, days];
}
Note that in javascript, doing x | 0 is the same as Math.floor(x).
It looks to me like your calculation for hours still has the days in it. Once you have established the days, just subtract those out when you calculate the hours.
var start = new Date("June 09, 2017 10:30:00");
var end = new Date("June 10, 2017 11:45:00");
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
console.log(time);
function display(a)
{
var minutes = a % 60;
var one_day=1000*60*60*24
var days = Math.ceil(a/one_day)
var hours = Math.trunc((a-(days*1440))/60);
var time = [hours,minutes,days];
return time;
}
Having said that, I highly recommend moment.js to handle this type of thing, if you can.
var startDateTime = 1497029400000;
var endDateTime = 1497120300000;
var timeDifference = endDateTime - startDateTime
// with the given dates, days equals 1.0520833333333333
// we want to extract the trailing decimal values using modulus to get the other times
function getTimeDifference(timeDifference) {
var days = timeDifference/1000/60/60/24
days >= 1
? var dayCount = Math.trunc(days); // store the day count
: var dayCount = 0; // it is less than one day
// get the remaining hours
var hours = (days % 1) * 24;
var hoursCount = Math.trunc((days % 1) * 24);
// get the remaining minutes
var minutesCount = Math.ceil((hours % 1) * 60);
}
I have an input hours which will be 0 to any hours, for example
25 hours... I need an output in days hours and minutes: 1 day 1 hour 0 min
I have tried and it returns days but help me to convert to days hrs and min
var flag_hours = 25;
if(flag_hours >=24)
{
var totaldays = flag_bookbefore/24;
alert(totaldays);
}
which gives output as : 1.0416666666666667
Thanks in advance!
Try this function: It gives you access to days hours and minutes separately.
function SplitTime(numberOfHours){
var Days=Math.floor(numberOfHours/24);
var Remainder=numberOfHours % 24;
var Hours=Math.floor(Remainder);
var Minutes=Math.floor(60*(Remainder-Hours));
return({"Days":Days,"Hours":Hours,"Minutes":Minutes})
}
var hours=27.3
var timeResult=SplitTime(hours)
console.log("27.3 hours translate to "+timeResult.Days+"Days "+timeResult.Hours+"Hours and "+timeResult.Minutes+"Minutes.")
Try this:
var days = Math.floor(flag_hours / 24);
var hours = Math.floor(flag_hours) % 24;
var minutes = (flag_hours - Math.floor(flag_hours)) * 60;
Not tested, might be horribly wrong.
Try this:
var hour = 47.5;
var day = 0;
var minute = parseInt((hour % 1)*60);
if (hour>24){
day = parseInt(hour / 24);
hour = parseInt(hour % 24);
}else{
hour = parseInt(hour);
}
alert (day);
alert(hour);
alert(minute);
check it in jsFiddle
I am trying to make a javascript timer that when initiated, starts counting up. The timer is just a visual reference from when a start button is clicked to when the end button is clicked.
I found a plugin online which works perfectly for counting down but I am trying to modify it to count up.
I hard coded a date way in the future. I am now trying to get the timer to start counting up to that date. This will be reset every time the start button is clicked.
This is the function I am working with. it works perfectly to count down but I cant figure out how to reverse it.
I thought it was something with how the differece was calculated but I believe it actually happens in the //calculate dates section.
Is there an easy way to reverse this math and have it count up instead?
Fiddle: http://jsfiddle.net/xzjoxehj/
var currentDate = function () {
// get client's current date
var date = new Date();
// turn date to utc
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// set new Date object
var new_date = new Date(utc + (3600000*settings.offset))
return new_date;
};
function countdown () {
var target_date = new Date('12/31/2020 12:00:00'), // Count up to this date
current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - target_date;
// if difference is negative than it's pass the target date
if (difference > 0) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
var interval = setInterval(countdown, 1000);
};
JSFiddle
var original_date = currentDate();
var target_date = new Date('12/31/2020 12:00:00'); // Count up to this date
var interval;
function resetCountdown() {
original_date = currentDate();
}
function stopCountdown() {
clearInterval(interval);
}
function countdown () {
var current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - original_date;
if (current_date >= target_date) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
interval = setInterval(countdown, 1000);
};
This OP already has an answer but that has issue with timezone , so this answer.
DownVoters care to comment.
Try this. Fiddle
var TargetDate = new Date('2015', '08', '04', 11, 11, 30) // second parameter is month and it is from from 0-11
$('#spanTargetDate').text(TargetDate);
$('#spanStartDate').text(new Date());
var Sec = 0,
Min = 0,
Hour = 0,
Days = 0;
var counter = setInterval(function () {
var CurrentDate = new Date()
$('#spanCurrentDate').text(CurrentDate);
var Diff = TargetDate - CurrentDate;
if (Diff < 0) {
clearInterval(counter);
$('#timer').text('Target Time Expired. test in fiddle')
} else {
++Sec;
if (Sec == 59) {
++Min;
Sec = 0;
}
if (Min == 59) {
++Hour;
Min = 0;
}
if (Hour == 24) {
++Days;
Hour = 0;
}
if (Sec <= Diff) $('#timer').text(pad(Days) + " : " + pad(Hour) + " : " + pad(Min) + " : " + pad(Sec));
}
}, 1000);
function pad(number) {
if (number <= 9) {
number = ("0" + number).slice(-4);
}
return number;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Target Time - <span id="spanTargetDate"></span>
<br/>
<br/>Start Time - <span id="spanStartDate"></span>
<br/>
<br/>Current Time - <span id="spanCurrentDate"></span>
<br/>
<br/>Timer (DD:HH:MM:SS) - <span id="timer"></span>
<br/>
<br/>