I would like to get the date difference:
var dateString='2015-04-07T10:46:25Z';
var dt = new Date(value);
var now = new Date();
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
var utc1 = Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate());
var utc2 = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
var days=Math.floor((utc2 - utc1) / _MS_PER_DAY);//this is 415
The result must be in this format: 415d, 03:06:33
What would be the best way to do that? I get date, but time is missing.
Try this
var datetime = new Date("2015-04-07T10:46:25Z");
var now = new Date();
if (datetime < now) {
var diffTime = now - datetime;
}else{
var diffTime = datetime - now;
}
var days = Math.floor(diffTime / 1000 / 60 / (60 * 24));
var dateDiff = new Date( diffTime );
var hour = dateDiff .getHours().toString().length == 1 ? '0' + dateDiff .getHours() : dateDiff .getHours();
var minute = dateDiff.getMinutes().toString().length == 1 ? '0' + dateDiff.getMinutes() : dateDiff.getMinutes();
var seconds = dateDiff.getSeconds().toString().length == 1 ? '0' + dateDiff.getSeconds() : dateDiff.getSeconds();
console.log(days + "d "+ hour + ":" + minute + ":" + seconds);
you need to use Modulus
var dt = new Date('2015-04-07T10:46:25Z');
var now = new Date();
var milSecondMil = 1000;
var secondMil = milSecondMil * 60;
var hourMil = secondMil * 60;
var dayMil = hourMil * 24;
var diff = now - dt;
var days = Math.floor(diff / dayMil);
var daysRemainder = diff % dayMil;
var hours = Math.floor(daysRemainder / hourMil);
var hoursRemainder = daysRemainder % hourMil;
var seconds = Math.floor(hoursRemainder / secondMil);
var secondsRemainder = hoursRemainder % secondMil;
var milSeconds = Math.floor(secondsRemainder / milSecondMil);
console.log(days + ' days - ' + hours + ' hours - ' + seconds + ' seconds - ' + milSeconds + ' mil');
I have done this way:
var dt = new Date(value);
var now = new Date();
var date1_ms = dt.getTime();
var date2_ms = now.getTime();
var diff=(date2_ms - date1_ms) / 1000;
var tm = new Date(null, null, null, null, null, Math.floor(diff % 86400)).toTimeString().split(" ")[0];
return Math.round(diff / (60 * 60 * 24)) + 'd, ' + tm;
Related
I have date string 2022-01-03T00:00:00.000Z, i want to find the difference between today and this day in days.
I tried this but not working as expected.
var d1 = Date.now();
var d2 = new Date('2020-01-03T00:00:00.000Z').getTime();
console.log(d1);
console.log(d2);
var hours = hoursDiff(d1, d2);
var daysDiff = Math.floor( hours / 24 );
console.log(daysDiff);
function hoursDiff(d1, d2) {
var minutes = minutesDiff(d1, d2);
var diff = Math.floor( minutes / 60 );
return diff;
}
function minutesDiff(d1, d2) {
var seconds = secondsDiff(d1, d2);
var diff = Math.floor( seconds / 60 );
return diff;
}
function secondsDiff(d1, d2) {
var millisecondDiff = d2 - d1;
var diff = Math.floor( ( d2 - d1) / 1000 );
return diff;
}
See comments in snippet:
var d = new Date();
// build a date with 0 hours, minutes, seconds
var d1 = new Date(d.getFullYear() + '-' + ("0" + d.getMonth()).slice(-2) + '-' + d.getDate() + 'T00:00:00.000Z').getTime();
// date to compare
var d2 = new Date('2022-04-27T00:00:00.000Z').getTime();
// to seconds / to minutes / to hours/ to days
console.log((d1 - d2) / 1000 / 60 / 60 / 24);
I am using this formula to calculate time between 2 different fields but result is in whole numbers and I need hours/minutes
time after dateFromString is example
var date1 = dateFromString(06: 00: 00);
var date2 = dateFromString(17: 30: 00);
var hours = Math.abs(date1 - date2) / 36e5;
return hours;
function dateFromString(isoDateString) {
var parts = isoDateString.match(/\d+/g);
var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
var isoDate = new Date(isoTime);
return isoDate;
}
Your code has some syntax errors, but try this, it should give you the time difference in an hours:minutes format:
var startTime = '06:00:00';
var endTime = '17:30:00';
var timeStart = new Date("01/01/2007 " + startTime);
var timeEnd = new Date("01/01/2007 " + endTime);
var minutesDiff = diff_minutes(timeStart, timeEnd);
var hoursAndMinsDiff = convertMinsToHrsMins(minutesDiff);
console.log(hoursAndMinsDiff)
function diff_minutes(dt2, dt1) {
var diff = (dt2.getTime() - dt1.getTime()) / 1000;
diff /= 60;
return Math.abs(Math.round(diff));
}
function convertMinsToHrsMins(mins) {
let h = Math.floor(mins / 60);
let m = mins % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return `${h}:${m}`;
}
Is that what you're looking for?
Use division to get the hours, and then get the minutes using the remainder operation.
Also, dateFromString() expects the string to have both the date and time, not just a time, and it needs to be a quoted string.
var date1 = dateFromString("2018-12-01 06:00:00");
var date2 = dateFromString("2018-11-30 17:30:00");
var diffmin = Math.floor(Math.abs(date1 - date2) / 60000);
var hours = Math.floor(diffmin/60);
var minutes = diffmin % 60;
console.log(hours, minutes);
function dateFromString(isoDateString) {
var parts = isoDateString.match(/\d+/g);
var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
var isoDate = new Date(isoTime);
return isoDate;
}
I want to make a countdown. Here's the algorithm :
var timeFinish, timeStart, timeNow, duration
timeStart <- the time when the document has ready
timeFinish <- timeStart + 1hour
timeNow <- get the time everytime (every second)
duration <- timeFinish - timeNow
output (duration)
I deliberately didn't write the algorithm for converting it into second etc (for shortening purpose, and I hope you get what I mean). Here's my code
$(document).ready(function() {
setInterval(countdown(), 1000);
function countdown() {
var hStart = new Date($(document).ready).getHours;
var mStart = new Date($(document).ready).getMinutes;
var sStart = new Date($(document).ready).getSeconds;
var secondTotalStart = (hStart * 3600) + (mStart * 60) + sStart;
var secondTotalFinish = secondTotalStart + 3600;
var hRunning = new Date().getHours;
var mRunning = new Date().getMinutes;
var sRunning = new Date().getSeconds;
var secondTotalRunning = (hRunning * 3600) + (mRunning * 60) + sRunning;
var duration = secondTotalFinish - secondTotalRunning;
var h = Math.floor(duration / 3600);
var m = Math.floor(duration % 3600) / 60;
var s = Math.floor(duration % 3600) % 60;
$("#countdown").html(h + " h : " + m + " m : " + s + " s");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
And my question is, how to get the timeStart? And is my code wrong?
I've corrected your code so you can look at mistakes:
$(document).ready(function() {
//below line: you must pass countdown as a function
setInterval(countdown, 1000);
var dt = new Date(); //get this out of countdown function
var hStart = dt.getHours();
var mStart = dt.getMinutes();
var sStart = dt.getSeconds();
var secondTotalStart = (hStart * 3600) + (mStart * 60) + sStart;
var secondTotalFinish = secondTotalStart + 3600;
function countdown() {
var cdt = new Date();
var hRunning = cdt.getHours();
var mRunning = cdt.getMinutes();
var sRunning = cdt.getSeconds();
var secondTotalRunning = (hRunning * 3600) + (mRunning * 60) + sRunning;
var duration = secondTotalFinish - secondTotalRunning;
var h = Math.floor(duration / 3600);
var m = Math.floor(duration % 3600 / 60);
var s = Math.floor(duration % 3600) % 60;
$("#countdown").html(h + " h : " + m + " m : " + s + " s");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
$(document).ready(function() {
var dTime = new Date(); //need to store the on-load time before set interval as a reference
setInterval(countdown, 1000);
function countdown() {
var hStart = dTime.getHours();//need to get the on-load hr, min and sec from the previously stored time.
var mStart = dTime.getMinutes();
var sStart = dTime.getSeconds();
var secondTotalStart = (hStart * 3600) + (mStart * 60) + sStart;
var secondTotalFinish = secondTotalStart + 3600;
var running = new Date()// store the current time into a variable
var hRunning = running.getHours();
var mRunning = running.getMinutes();
var sRunning = running.getSeconds();
var secondTotalRunning = (hRunning * 3600) + (mRunning * 60) + sRunning;
var duration = secondTotalFinish - secondTotalRunning;
var h = Math.floor(duration / 3600);
var m = Math.floor(duration % 3600) / 60;
var s = Math.floor(duration % 3600) % 60;
$("#countdown").html(h + " h : " + m + " m : " + s + " s");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
Did minor corrections. hope this helps
edit:
added some useful comments.
So I have two strings in javascript:
old_date = "2010-11-10 07:30:40";
new_date = "2010-11-15 08:03:22";
I want to find the difference between these two dates, but I am totally at a loss :(
I tried to do the following:
old_date_obj = new Date(Date.parse(old_date));
new_date_obj = new Date(Date.parse(new_date));
But it is giving me error. However that is only start of my woes...I need to show the difference as:
Difference is X Days, Y hours and Z minutes
Can JavaScript/jQuery gurus help me please? Much appreciated...
<script>
function Calculate() {
old_date = "2010-11-10 07:30:40";
new_date = "2010-11-15 08:03:22";
old_date_obj = new Date(Date.parse(old_date, "dd/mm/yyyy HH:mm:ss"));
new_date_obj = new Date(Date.parse(new_date, "dd/mm/yyyy HH:mm:ss"));
var utc1 = Date.UTC(new_date_obj.getFullYear(), new_date_obj.getMonth(), new_date_obj.getDate());
var utc2 = Date.UTC(old_date_obj.getFullYear(), old_date_obj.getMonth(), old_date_obj.getDate());
alert(Math.floor((utc2 - utc1) / (1000 * 60 * 60 * 24)));
}
</script>
simply add in you date and it will work for you.
"2010-11-10T07:30:40+01:00"
for more detail check this answer
Answer in detail
<script type="text/javascript">
// The number of milliseconds in one day, hour, and minute
var ONE_DAY = 1000 * 60 * 60 * 24;
var ONE_HOUR = 1000 * 60 * 60;
var ONE_MINUTE = 1000 * 60;
var old_date = "2010-11-10T07:30:40";
var new_date = "2010-11-15T08:03:22";
// Convert both dates to milliseconds
var old_date_obj = new Date(old_date).getTime();
var new_date_obj = new Date(new_date).getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(new_date_obj - old_date_obj)
// Convert back to days, hours, and minutes
var days = Math.round(difference_ms / ONE_DAY);
var hours = Math.round(difference_ms / ONE_HOUR) - (days * 24) - 1;
var minutes = Math.round(difference_ms / ONE_MINUTE) - (days * 24 * 60) - (hours * 60);
alert('Difference is ' + days + ' days, ' + hours + ' hours and ' + minutes + ' minutes.' );
</script>
<script type="text/javascript">
function getDates(strDate1, strDate2) {
/*Now strDate1 and strDate2 string. So we should convert them to javascript datetime value.*/
var tempDate1 = strDate1.split(/\-|\s/)
var date1 = new Date(tempDate1.slice(0,3).reverse().join('/')+' '+tempDate1[3]);
var tempDate2 = strDate2.split(/\-|\s/)
var date2 = new Date(tempDate2.slice(0,3).reverse().join('/')+' '+tempDate2[3]);
var obj1 = $.datepicker.parseDate('dd.mm.yy', $("#date1").val());
var obj2 = $.datepicker.parseDate('dd.mm.yy', $("#date2").val());
console.log(findDifferentDate(obj1, obj2));
}
function findDifferentDate(obj1, obj2){
var date1 = getFormattedDate(obj1);
var date2 = getFormattedDate(obj2);
var year = date1.getFullYear() - date2.getFullYear();
var day = date1.getDate() - date2.getDate();
var month = date1.getMonth() - date2.getMonth();
var seconds = date1.getSeconds() - date2.getSeconds();
var minutes = date1.getMinutes() - date2.getMinutes();
var hour = date1.getHours() - date2.getHours();
return 'Difference is' + day + 'Days' + month + 'Months' + year + 'Years' + seconds + 'Seconds' + minutes + 'Minutes' + hour + 'Hours';
}
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return day + '.' + month + '.' + year;
}
</script>
If you call getDates method with your dates and then u can see difference time in the console.
var old_date = "2010-11-15 07:30:40";
var new_date = "2010-11-15 08:03:22";
var old_date_obj = new Date(Date.parse(old_date));
var new_date_obj = new Date(Date.parse(new_date));
var diffMs = Math.abs(new_date_obj - old_date_obj);
var diffDays = Math.round(diffMs / 86400000); // days
var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
https://jsfiddle.net/yps2wb58/1/
this is my javascript code to calculate time difference:
var startTime = '11:30 am';
var EndTime = '1:30 pm';
var ed = EndTime.split(':');
var st = startTime.split(':');
var sub = parseInt(ed[0]) * 60 + parseInt(ed[1]);
var sub1 = parseInt(st[0]) * 60 + parseInt(st[1]);
i am getting outout:-600
i want difference in output as:2 hour.
can anybody figure out whats wrong with my code??
I would suggest
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
Check this fiddle
http://jsfiddle.net/shubhambhave/D9M8a/
Please, use more your mind.
First, you're not even looking at the AM or PM.
If you are sure your times will look like this (and not timestamp or anything else), you can do this (I try to keep your logic here):
var startTime = '11:30 am';
var endTime = '1:30 pm';
var st = startTime.split(':');
var ed = endTime.split(':');
if ((st[1].split(' '))[1] == 'pm')
st[0] = parseInt(st[0]) + 12;
if ((ed[1].split(' '))[1] == 'pm')
ed[0] = parseInt(ed[0]) + 12;
st[1] = (st[1].split(' '))[0];
ed[1] = (ed[1].split(' '))[0];
var diff = ((ed[0] * 60 + ed[1] * 60) - (st[0] * 60 + st[1] * 60)) / 60;
In fact, you forgot to remove the 'am' part of the time.
You also forget to calculate it.
This code can be refactored, but i'm not gonna do all the job.