Calculate difference between 2 timestamps using javascript - 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(),
});

Related

setHours() javascript returns a diffrent format then expected

I have this situation where I am in need of using the JavaScript
setTime()
So that I can modify the time, according to a number of seconds I have. For example I want to know what time it was 1400 sec ago.
I come to the conclusion that my cleanest and best solution it would be to use a combination of
getDate() and setHours() - setMinutes() - setSeconds() like in the example in this link:
https://codepen.io/Jaquelline/pen/rPgOKj?editors=1011
function myFunction() {
var myTime = new Array();
for(i=0; i <3599; i++){
var d = new Date();
var currentI = 3599-i;
myTime[i] = new Array();
myTime[i] = {
x: i,
y: d.setHours(d.getHours()-1) + ':' + d.setMinutes(d.getMinutes()) + ':'+ d.setSeconds(d.getSeconds()+currentI)
};
}
var s = JSON.stringify(myTime);
document.getElementById("cTimeArray").innerHTML =s;
var t = new Date();
t.setHours(t.getHours()-1);
t.setHours(t.getMinutes());
t.setHours(t.getSeconds()+1200);
document.getElementById("cTime").innerHTML =t;
}
The s variable returns something like this:
[{"x":0,"y":"1550821508351:1550821508351:1550825107351"},
{"x":1,"y":"1550821508351:1550821508351:1550825106351"},
While t returns :
Sun Apr 14 2019 08:45:08 GMT+0200 (Mitteleuropäische Sommerzeit)
If you simply want to know the time 1400 seconds ago, then why not just subtract 1400 seconds from the current time?
var past = new Date((new Date().getTime()) - 1400 * 1000);
getTime() returns the timestamp representing the date/time in milliseconds, hence the multiplication of 1400 by 1000.
You don't show the correct value.
Set d before and use the getters to show the value.
var myTime = new Array();
for (i = 0; i < 3599; i++) {
var d = new Date();
var currentI = 3599 - i;
myTime[i] = {};
d.setHours(d.getHours() - 1);
d.setMinutes(d.getMinutes());
d.setSeconds(d.getSeconds() + currentI);
myTime[i] = {
x: i,
y: d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
};
}
var s = JSON.stringify(myTime);
console.log(s);

take a date string, add a class to span if expiration date is less than 2 weeks from now

i've been stuck on this problem for a while now and I am ready to pull my hair out :). I have to add a class to a span if a campaign date is expiring in 2 weeks or less. The date retrieved is a string in the following format
07/26/2017
when I run this function, I am passing the datestring as an argument since the method will be attached to the var which holds the string. But for whatever reason this logic isn't working. Am I totally screwing this up? It's failing silently somewhere. Thank you. I know it should be easy but I am caught in a loop.
campMethods.EndDateAlert = function (dateString) {
var currentDate = new Date ();
var twoWeeks = new Date ();
twoWeeks.setDate(currentDate.getDate() + 14)
var $EndDateSpan = $('.campaign-end-date');
if (dateString <= twoWeeks) {
$EndDateSpan.addClass('red');
}
return dateString;
};
You can do that with some Math. The key is, 2 weeks = 14 days.
Here is Pure Javascript example for you:
var date = "07/26/2017".split("/");
var formatedDate = (date[2] + '' + date[0] + '' + date[1]);
var currentDate = new Date();
var today = currentDate.getFullYear() +''+ ("0" + (currentDate.getMonth() + 1)).slice(-2)+''+("0" + currentDate.getDate()).slice(-2);
var compareDay = formatedDate - today;
if(compareDay < 14){// 14 day = 2 week
// do something for less than 2 weeks
console.log('Less than 2 weeks will be expired');
} else {
// also can do something
console.log('more than 2 weeks will be expired.');
}
Javascript Date Reference
Try comparing milliseconds of the dates.
We know that there are 1000 * 60 * 60 * 24 * 14 = 1209600000 milliseconds in two weeks, knowing this we can add 1209600000ms to the current date and compare this to the milliseconds of the due date.
let dueDate = new Date('07/26/2017');
if(Date.now() + 1209600000 > dueDate.getMilliseconds()){
//do stuff
}

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.

Find difference between two dates with javascript [duplicate]

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.

Convert input type text into date format

I have one input type text:
<input type="text" id="policyholder-dob" name="policyholder-dob" />
I want to type number in this field in mm/dd/yyyy format:
like 01/01/2014
This is my js code but its not working, what mistake have I made?
function dateFormatter(date) {
var formattedDate = date.getDate()
+ '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
return formattedDate;
}
var nextduedate = $("#policyholder-dob").val();
var dateFormatDate = nextduedate.slice(0, 2);
var dateFormatMonth = nextduedate.slice(2, 4);
var dateFormatYear = nextduedate.slice(4, 8);
var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear;
var againNewDate = new Date(totalFormat);
againNewDate.setDate(againNewDate.getDate() + 1);
var todaydate = dateFormatter(againNewDate);
$("#policyholder-dob").prop("value", todaydate);
Any help will be really appreciated.
Thankfully, your input is consistently in this format:
mm/dd/yyyy
So you can convert it to a Date object through a custom function, such as:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2],
temp = [];
temp.push(y,m,d);
return (new Date(temp.join("-"))).toUTCString();
}
Or:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2];
return (new Date(y + "-" + m + "-" + d)).toUTCString();
}
Etc..
Calling it is easy:
stringToDate("12/27/1963");
And it will return the correct timestamp in GMT (so that your local timezone won't affect the date (EST -5, causing it to be 26th)):
Fri, 27 Dec 1963 00:00:00 GMT //Late december
Example
There are various ways to accomplish this, this is one of them.
I'd suggest moment.js for date manipulation. You're going to run into a world of hurt if you're trying to add 1 to month. What happens when the month is December and you end up with 13 as your month. Let a library handle all of that headache for you. And you can create your moment date with the string that you pull from the val. You substrings or parsing.
var d = moment('01/31/2014'); // creates a date of Jan 31st, 2014
var duration = moment.duration({'days' : 1}); // creates a duration object for 1 day
d.add(duration); // add duration to date
alert(d.format('MM/DD/YYYY')); // alerts 02/01/2014
Here's a fiddle showing it off.

Categories

Resources