JavaScript calculate difference in seconds between to datetime - javascript

I am new to JavaScript and have done some research, however I cannot find a straightforward solution to relatively simple problem. I have a following var:
var recordDate = '2016-04-20 17:52:33';
I need to get the difference between now and recordDate in seconds. What would be the most efficient way to achieve it?

Try to convert recordDate to a Date Object first
var match = recordDate.match(/^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)\:(\d+)$/);
var date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]);
var currentDate = new Date();
var differenceInSeconds = Math.abs(date.getTime() - currentDate.getTime())/1000;
DEMO
var recordDate = '2016-04-20 17:52:33';
var match = recordDate.match(/^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)\:(\d+)$/);
var date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]);
alert(date.toString());
var currentDate = new Date();
var differenceInSeconds = Math.abs(date.getTime() - currentDate.getTime())/1000;
alert(differenceInSeconds);

Set the date record like this:
var recordDate = new Date('2016-04-20 17:52:33');
var currentTime = new Date();
And then calculate it like this:
(currentTime - recordDate) / 1000 = {Seconds in between}
Additional comment:
Additional explanation why I am not using abs is because it looks like the purpose for this it to display like where in stackoverflow - edited 5 seconds ago or similar, when the currentTime will never be less then the record date and therefore one calculation and dependency less.

Related

node red / JS : calculate time elapsed

I have no experience with JS, but I need to get the time from a node red flow where the payload return the date in this format : 2022-09-03 08:23:39.806170+00:00 and then compare to the sensor.time which is the current date to return the elapsed time.
so something like this VarElapsed to (MyPayload - sensor.time)
again I have no experience with JS so I would thing this would be the result but thatss probably doesn't make any sense...
var d=new Date();
var start_time=payload
d=new Date();
var end_time=d.getTime()
var difference =end_time-start_time;
The format is cool to instantiate a new Date object.
var payload = "2022-09-03 08:23:39.806170+00:00";
var start_time = (new Date(payload)).getTime();
var d = new Date();
var end_time = d.getTime()
var difference = end_time - start_time;
console.log("difference in ms: ", difference)

Get days difference in two dates format (YYYY/MM/DD hh:mm)?

I'm trying to get the diference between 2 dates that look like this:
2018/10/05 13:59
But my issue is with my code, it always retunr NaN.
This is my current code:
var start = '2018/10/05 13:59';
var end = '2018/10/05 17:59';
var converted_start = start.replace("/", "-");
var converted_end = end.replace("/", "-");
// end - start returns difference in milliseconds
var diff = new Date(converted_end - converted_start);
// get days
var days = diff/1000/60/60/24;
alert(days);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I tried to replace the / with - in my code but that didn't fix the issue!
Could someone please advice on this issue?
Thanks in advance.
var start = '2018/10/05 13:59';
var end = '2018/10/05 17:59';
var startDate = Date.parse(start);
var endDate = Date.parse(end);
var diff = new Date(endDate - startDate);
var days = diff/1000/60/60/24;
this works for me
You can use the following to get days difference in two dates format (YYYY/MM/DD hh:mm):
var start = new Date('2018/10/05 13:59');
var end = new Date('2018/10/05 17:59');
// get hours
var hours= (end-start)/3600000;
alert(hours);

Only show data on html page where javascript date is within last 10 days

I have javascript array in which the date coming in is in this format
2015-11-25T17:54:19.033
However, I am not really concerned with the time
so I end up with
11/25/15
What I want to do in my loop is to LOOK at the date ( either 2015-11-25T17:54:19.033 or 11/25/15 , whatever is easier) and just set a variable to "NEW" if it is within the last 10 days
I was attempted to play around with this code and it does not give me what I want at all
var dt = "11/25/15";
var today = new Date()
var priorDate = new Date().setDate(today.getDate()-10)
console.log(dt);
console.log(today);
console.log(priorDate);
pseudo code of what i WANT
if ( dt <= today ) {
x = "NEW";
}
So my thoughts are that it need to be in Date objects in javascript but i'm not sure
Update
So say in a loop i have these variables that occur
for ....
dt = 9/13/15
Output = 9/13/15
next time in loop
dt = 11/24/15
Output = NEW - 11/24/15
Working jsfiddle
http://jsfiddle.net/bthorn/yr009hwd/
You are correct. You need to convert the string date to a date time object in javascript to do the comparison.In order to do the comparison, you need to get the millisec of the dates using getTime()
var dt = new Date("11/22/2015");
var today = new Date();
if ( dt.getTime() < today.getTime() ) {
alert('Past');
}
else
alert('future');
To check if the date difference is within 10 days:
var dt = new Date("11/12/2015");
var today = new Date();
var dateDiffDays = Math.ceil((Math.ceil(dt.getTime() - today.getTime()))/(1000 * 3600 * 24));
if( dateDiffDays >= -10 && dateDiffDays <= 10)
alert('date within 10 days');
Depending on the format of your date string, you can probably just do:
var dateToTest = new Date(dt);
//get 10 days earlier
dateToTest.setDate(dateToTest.getDate() - 10);
var today = new Date();
if ( dateToTest < today ) {
x = 'NEW';
}
//see if a date is within the last 10 days
var tenDaysAgo = new Date(); //current date
tenDaysAgo.setDate(tenDaysAgo.getDate() - 10); //ten days ago
//if you don't care about the time
tenDaysAgo.setHours(0);
tenDaysAgo.setMinutes(0);
tenDaysAgo.setSeconds(0);
tenDaysAgo.setMilliseconds(0);
var someDateToTest = new Date('11-1-2015');
if (tenDaysAgo > someDateToTest) {
//this is new
x = 'NEW';
}

Efficiently create Javascript Date from Today -1 Years (time) in Unix time

I currently am using this to create a Unix time stamp for time (now) -1 year's time.
Can someone please share a better and more efficient way to do this?
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var lastYear = parseInt(currentYear) - 1;
var lastYearDateObj = new Date(lastYear, currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes());
var lastYearTime = lastYearDateObj.getTime() / 1000;
Thank you!
I don't understand what your division by 1000 is about. You can add it to the end if you like:
var date = new Date();
date.setFullYear(date.getFullYear() - 1);
// date.getTime() / 1000 // if you want.

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;

Categories

Resources