Find difference between two dates with javascript [duplicate] - javascript

This question already has answers here:
Difference between dates in JavaScript
(8 answers)
Closed 8 years ago.
I am trying to find the difference between two dates. The dates are got with jquery and I am using datejs too. When using datejs it picks up my date as US thinking it is MM/DD/YYYY instead of dd-mm-yyyy. My result for difference is NaN. How do I work this out. Am I miles out or anywhere near close?
var msMinute = 60*1000,
msDay = 60*60*24*1000;
start = $('#reconcile_start_date').val(); // 10-12-2014 | dd-mm-yyyy
end = $('#reconcile_end_date').val(); // 15-12-2014 | dd-mm-yyyy
start = new Date(start);
end = new Date(end);
console.log(Math.floor((end - start) / msDay) + ' full days between ' + end + ' and ' + start);
difference = Math.floor((end - start) / msDay);
if(difference > 30){}

try this:
$(document).ready(function(){
var msMinute = 60*1000;
var msDay = 60*60*24*1000;
var start = '10-12-2014'; // October 12
var statarr=start.split('-');
var end = '12-15-2014'; // December 15
var endarr=end.split('-');
var dstart = new Date(statarr[0]+'/'+statarr[1]+'/'+statarr[2]).getTime();
var dend = new Date(endarr[0]+'/'+endarr[1]+'/'+endarr[2]).getTime();
var diff = parseInt(dend-dstart);
console.log(Math.floor(diff / msDay) + ' full days between ' + end + ' and ' + start);
difference = Math.floor((end - start) / msDay);
if(difference > 30){
}
});
// for UK formate use this:
var start = '12-10-2014'; // October 12
var statarr=start.split('-');
var end = '15-12-2014'; // December 15
var endarr=end.split('-');
var dstart = new Date(statarr[1]+'/'+statarr[0]+'/'+statarr[2]).getTime();
var dend = new Date(endarr[1]+'/'+endarr[0]+'/'+endarr[2]).getTime();
and rest is same.

The issue is around the parsing of the dates, by default JS wont parse the date in the format.
Some more examples on how to convert the date format from UK format can be found (Why does Date.parse give incorrect results?)
More information of the dateString param, formats and browser behaviour - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
See this sample. http://jsbin.com/fayerihipu/2/
$(document).ready(function(){
var msMinute = 60*1000,
var msDay = 60*60*24*1000;
var start = '10-12-2014'; // October 12
var end = '12-15-2014'; // December 15
var dstart = new Date(start).getTime();
var dend = new Date(end).getTime();
var diff = parseInt(dend-dstart);
console.log(Math.floor(diff / msDay) + ' full days between ' + end + ' and ' + start);
difference = Math.floor((end - start) / msDay);
if(difference > 30){
}
});

Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, and almost all browsers also support yyyy/mm/dd as well.
So you need to do something like this to parse your dates:
var parts = start.split('-');
start = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
//Date uses zero-based month numbers, and so we have to subtract one from the month number
Take a look here for more details.

Related

How to calculate the number of gaps between two dates in js

I have two date with time:
YY:MM:DD hh:mm
This is the time period
I need to calculate gap and divide it into 'n' equal parts.
In order to build a graph
Pls Help
Because date is actually saved as an integer and only shown as
YY:MM:DD hh:mm
You can actually just take the two date variables and devide them by the n
gap = (date1 - date2)/n
and then you can get the intervals by just adding the gap multiple times
for(var i = 1; i <= n; i++){
newDate[i] = new Date(date2 + gap*i);
}
something like this?
you can operate directly with dates in javascript
var date1 = new Date(2017, 01, 01, 10, 15, 00);
var date2 = new Date(2016, 12, 01, 10, 14, 45);
var dateDiff = new Date(date1-date2); //this will return timestamp
var years = dateDiff.getFullYear() - 1970; //init date always is 1970
var months = dateDiff.getMonth();
var days = dateDiff.getDate();
var minutes = dateDiff.getMinutes();
var seconds = dateDiff.getSeconds();
alert(years + " years.\r " +
months + " months\r" +
days + " days\r" +
minutes + " minutes\r" +
seconds + " seconds");
I would suggest that you try out the momentjs library. It provides powerful functionalities for you to conveniently work with date objects.
For example, given 2 string dates that are properly formatted, you can get the precise difference between the 2 times easily like so:
let time1 = moment("04/09/2013 15:00:00");
let time2 = moment("04/19/2013 18:20:30");
let diffMilliseconds = time1.diff(time2); // gives the time difference in milliseconds
let diffDays = time1.diff(time2, 'days'); // gives the time difference in days
You can use the date object to convert the given time format to timestamp and then find difference between timestamp.
For example:
var date1 = "2017-03-04 11:22:22"
var date2 = "2017-03-04 13:11:42"
var timestamp1 = Date.parse(date1, "YYYY-MM-DD HH:mm:ss")
var timestamp2 = Date.parse(date2, "YYYY-MM-DD HH:mm:ss")
var difference = timestamp2 - timestamp1;
console.log(difference) //in milliseconds
Now you can divide the difference in to n parts and add to timestamp1 to get following timestamp based on difference/n interval.

Calculating the difference between 2 dates using the UK date standard of dd/mm/yyyy [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 9 years ago.
I need your help.
How can I compare 2 dates and finding out what the date difference is, using the date format of dd/mm/yyyy? (uk date standard)
Ie.1
var date1 = "26/11/2013"
var date2 = "29/11/2013"
if (date1 < date2) { difference is -3 }
Ie.2
var date1 = "26/11/2013"
var date2 = "22/11/2013"
if (date1 > date2) { difference is +4 }
Ie.3
var date1 = "26/11/2013"
var date2 = "26/11/2013"
if (date1 > date2) { difference is 0 }
Use the Date object:
var date1 = '26/11/2013'.split('/');
var date2 = '29/11/2013'.split('/');
var start = new Date(date1[2], +date1[1]-1, date1[0]);
var end = new Date(date2[2], +date2[1]-1, date2[0]);
alert((start.getTime() - end.getTime()) / (1000*60*60*24));
You probably want to add some error checking but you get the idea
split Date into y m d
create new Dates
then use code like this. (Java)
public String get_duration_from_date(Date date1, Date date2) {
TimeUnit timeUnit = TimeUnit.SECONDS;
long diffInMillies = date2.getTime() - date1.getTime();
long s = timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
long days = s / (24*60*60);
long rest = s - (days*24*60*60);
long std = rest / (60*60);
long rest1 = rest - (std*60*60);
long min = rest1 / 60;
long sec = s % 60;
String dates ="";
if (days > 0)
dates += int_to_str((int)days) + " " + grs(R.string.days) + " ";
dates += fill2((int)std) + "h ";
dates += fill2((int)min) + "m ";
dates += fill2((int)sec) + "s ";
return dates;
}
If you really want to stick to the format, you could set a new date like this
var date1 = "21/11/2013"
, date1Obj = new Date(date1.split('/').reverse());
Then either make use of moment.js as Andreas mentioned or compare the dates yourself
var date1 = "21/11/2013"
, date2 = "29/11/2013"
, d1 = new Date(date1.split('/').reverse())
, d2 = new Date(date2.split('/').reverse());
if (d1 < d2){ console.log((d1.getTime()-d2.getTime())/86400000 + ' days') }

Calculate difference between 2 timestamps using javascript

I have to calculate the difference between 2 timestamps. Also can you please help me with conversion of a string into timestamp. Using plain javascript only. NO JQUERY.
Here's my function:
function clearInactiveSessions()
{
alert("ok");
<c:if test="${not empty pageScope.sessionView.sessionInfo}">
var currentTime = new Date().getTime();
alert("curr:"+currentTime);
var difference=new Date();
<c:forEach items="${pageScope.sessionView.sessionInfo}" var="inactiveSession">
var lastAccessTime = ${inactiveSession.lastUpdate};
difference.setTime(Maths.abs(currentTime.getTime()-lastAccessTime.getTime()));
var timediff=diff.getTime();
alert("timediff:"+timediff);
var mins=Maths.floor(timediff/(1000*60*60*24*60));
alert("mins:"+mins);
if(mins<45)
clearSession(${item.sessionID});
</c:forEach>
</c:if>
}
i am posting my own example try implement this in your code
function timeDifference(date1,date2) {
var difference = date1.getTime() - date2.getTime();
var daysDifference = Math.floor(difference/1000/60/60/24);
difference -= daysDifference*1000*60*60*24
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var secondsDifference = Math.floor(difference/1000);
console.log('difference = ' +
daysDifference + ' day/s ' +
hoursDifference + ' hour/s ' +
minutesDifference + ' minute/s ' +
secondsDifference + ' second/s ');
}
Based on the approved answer:
function(timestamp1, timestamp2) {
var difference = timestamp1 - timestamp2;
var daysDifference = Math.floor(difference/1000/60/60/24);
return daysDifference;
}
A better alternative would be using window.performance API.
const startTime = window.performance.now()
setTimeout(()=>{
const endTime = window.performance.now()
console.log("Time Elapsed : ",endTime-startTime) // logs ~2000 milliseconds
}, 2000)
If your string is Mon May 27 11:46:15 IST 2013, you can convert it to a date object by parsing the bits (assuming 3 letter English names for months, adjust as required):
// Convert string like Mon May 27 11:46:15 IST 2013 to date object
function stringToDate(s) {
s = s.split(/[\s:]+/);
var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun':5,
'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11};
return new Date(s[7], months[s[1].toLowerCase()], s[2], s[3], s[4], s[5]);
}
alert(stringToDate('Mon May 27 11:46:15 IST 2013'));
Note that if you are using date strings in the same timezone, you can ignore the timezone for the sake of difference calculations. If they are in different timezones (including differences in daylight saving time), then you must take account of those differences.
A simple deal to get the time difference.
var initialTime = new Date();
var finalTime = new Date();
console.log({
days: finalTime.getDay() - initialTime.getDay(),
hours: finalTime.getHours() - initialTime.getHours(),
minutes: finalTime.getMinutes() - initialTime.getMinutes(),
seconds: finalTime.getSeconds() - initialTime.getSeconds(),
milliseconds: finalTime.getMilliseconds() - initialTime.getMilliseconds(),
});

Get time difference in javascript ISO format

I have a datetime in ISO format i.e.
2012-06-26T01:00:44Z
I want to get the time difference from current time. How can I achieve this using javascript or javascript library Date.js or jquery
This will give you the difference in milliseconds, you can then format it as you want
var diff = new Date("2012-06-26T01:00:44Z") - new Date();
Try this:
var someDate = new Date("2012-06-26T01:00:44Z");
var now = new Date();
var one_day = 1000 * 60 * 60 * 24;
var diff = Math.ceil((someDate.getTime()-now .getTime())/(one_day))
alert(diff)
Example fiddle
You can obviously amend the one_day variable to get the difference in the unit you require.
I would suggest converting ISO format to something that works cross browser.
Try this,
var d = "2012-06-26T01:00:44Z";
var someDate = new Date(d.replace(/-/g,'/').replace('T',' ').replace('Z',''));
alert(someDate - new Date());
Edit:
I guess, you need pretty time
Try this awesome code
Edit 2:
You needed reverse, so try this instead
var old_date = new Date();
alert('Old date: ' + old_date.toGMTString())
var new_date = new Date(old_date.setMinutes(old_date.getMinutes() - 5));
alert('Date 5 minutes before: ' + new_date.toGMTString());
If you need timestamp,
alert(new_date.getTime());
in order to format date you can use this function to get the desire format of the date and you can easily change the position of day , month and year.
function convertFormat(inputDate)
var date = new Date(inputDate);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear();
var fullYear = year + '/' + month + '/' + day
return fullYear;

Javascript: wrong date calculation

So I just have posted a question about this code (which was answered):
$(document).ready(Main);
function Main() {
ConfigDate();
}
function ConfigDate() {
var currentTime = new Date();
var dayofWeek = currentTime.getDay();
var daysSinceThursday = (dayofWeek + 3) % 7
var lastThursday = new Date(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
$("#last_thursday").text(yyyy + " / " + mm + " / " + dd);
}
The problem now is that the date that appears in my cell is 1969 / 12 / 31 (which isn't even a thursday).
Did I do something wrong while calculating last thursday date?
This is because .getDate() returns the day of the month. So you are building your date based on a serial number of something less than 30, which won't even set your seconds above 1.
Use .setDate() instead of building a new date:
date.setDate(date.getDate() - daysSinceThursday);
.setDate() will modify your existing date object, it doesn't return a new date.
You're trying to set a Date based only on the day of the month of the last Thursday. Try something like this:
var daysSinceThursday = (dayofWeek + 3) % 7;
var lastThursday = new Date(currentTime.getTime());
lastThursday.setDate(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
http://jsfiddle.net/rAuRF/3/

Categories

Resources