Javascript caching issue with rails - javascript

I have installed gem 'auto-session-timeout' to automatically log users off of inactive sessions. I want to give the user a 2 minute warning before the session times out
I added the following to my application.html.erb
<%= javascript_tag do %>
var d = new Date('<%= session[:auto_session_expires_at] %>');
setInterval(function(){
var d = new Date('<%= session[:auto_session_expires_at] %>');
var e = new Date();
var f = e.getTime();
var diff = d - f ;
alert(d + " | " + diff);
if (diff < 120000) {
// alert("Your session is about to timeout in less than 2 minutes " + diff);
}
}, 10000);
<% end %>
My goal is to use the if (diff < 120000) statement to show an alert 2 minutes from logout.
The code above gets the session variable set by auto-session-timeout and then subtracts it from the current date (from js's getTime()) and comes up with a diff.
It is ALMOST working properly. If interact with the app, the counter gets reset. However, it seems like the old counter keeps running.
In other words if I look at the results of the alert statement that is not remarked out, I can see the datetime that is in the session variable and the calculated diff. Below I am only showing the minutes and sessions that are shown for simplicity.
25:22 168134 -- first alert box - shows the contents of the session var and also shows the calculated diff or milliseconds remaining.
25:22 143249 -- second alert box -- everything is as expected.
25:22 120816 -- So, it is counting down correctly with the correct info from the session variable
Now, if I interact with the app, auto session timeout resets the session variable auto_session_expires_at.
26:13 158345 -- OK - exactly what I would expect . The Javascript is picking up the new session variable and it recalcualtes the diff.
25:22 86327 -- BUT now I'm seeing the previous session variable and the diff calculator is still running
The cycle above will then keep repeating between the 'good' and 'old' session variable and diff. I think there is some kind of caching going on but I can't pinpoint it.
this behavior is repeatable for me
=======================================================
HTML from when I first open the app
/<![CDATA[
var d = new Date('2016-05-06 15:58:19 -0400');
setInterval(function(){
var d = new Date('2016-05-06 15:58:19 -0400');
var e = new Date();
var f = e.getTime();
var diff = d - f ;
alert(d + " | " + diff);
if (diff < 120000) {
// alert("Your session is about to timeout in less than 2 minutes " + diff);
}
}, 10000);
//]]>
HTML from after I click on a nav item. You can see that the date grabbed from the session variable changes
/<![CDATA[
var d = new Date('2016-05-06 15:58:48 -0400');
setInterval(function(){
var d = new Date('2016-05-06 15:58:48 -0400');
var e = new Date();
var f = e.getTime();
var diff = d - f ;
alert(d + " | " + diff);
if (diff < 120000) {
// alert("Your session is about to timeout in less than 2 minutes " + diff);
}
}, 10000);
//]]>
</script>

#SanF was right about the clearInterval. Here is the revised code. It's a lot different from what I started out with.
<% if current_user %>
<%= javascript_tag do %>
// --------------------------------------------------------------------------------------------------------
// This script enhances the functionality of the auto_session_timeout gem
//
// this script will give the user a warning at a specified time before they will be automatically logged out
// from their session.
//
// The polling interval is set in var myVar = setInterval(myTimer, 10000); where 10000 = 10 seconds
// That should be set to about 1000 so that the login screen appears as soon as possible when
// the user comes to a screen from a timed out session.
//
// The time before logout for the warning is set in if (diff < 120000) 120000 = 120 seconds
//
// The timeout itself is contrlled by the auto_session_timeout gem and the setting in the application
// controller ' auto_session_timeout 4.minutes' . Make sure that the time set there is LONGER than the
// time set below for the warning
// ---------------------------------------------------------------------------------------------------------
clearTimer(); // clear the warning timer if it has been set previously
var diff = 0; // Initialize the difference calculation
var b = new Date();
var f = new Date();
var e = new Date();
var current_time = e.getTime(); // get the current time from the system
expires = new Date('<%= session[:auto_session_expires_at] %>'); // get the expiration time set by auto session expires.
var myVar = setInterval(myTimer, 5000); // this calls myTimer and runs it at intervals specified. 1000 = 1 second
// ------------------------------------ myTimer --------------------------------------------------
// This function is called with a setInterval so that it runs at a set interval depending on the number
// passed to var myVar = setInterval(myTimer, 1000); above. It gets the session variable
// containing the expires at date/time and also the current time. If the difference is less than the value set
// a warning is shown via an alert box and then the function is cleared.
// ------------------------------------------------------------------------------------------------
function myTimer() {
var diff = 0; // Initialize the difference between expires date/time and current date/time
var expires_raw = '<%= session[:auto_session_expires_at] %>' // Get the raw session variable from rails
// we need to parse the date above to be like var d = new Date('2016-05-10T13:50:12-04:00');
var exp_date = expires_raw.slice(0,10); // grab the date
var exp_time = expires_raw.slice(11,19); // grab the time H M S
var exp_tzh = expires_raw.slice(20,23); // grab the hour part of the timezone with the -
var exp_tzm = expires_raw.slice(23,25); // grab the minute part of the timezone which should be 00
var expires_parsed = exp_date + "T" + exp_time + exp_tzh + ":" + exp_tzm; // Parse it all together. Date plus a constant 'T' , time, time zone hour, colon, timezone min
var expires_parsed_time = new Date(expires_parsed); // take expires_parsed and create a date/time from it
var expires_parsed_time_iso = expires_parsed_time.toISOString(); // Convert expires_parsed_time to an ISO string - This step is KEY to making this
// work with IE 11 and firefox. They need the date from a strict ISO format
var expires_final = new Date(expires_parsed_time) // create a date from the expires_parsed_time
var expires_parsed_final = new Date(expires_parsed_time) // This is the final date that is fed to the diff variable
var e = new Date(); // set up a new date for the current time
current_time = e.getTime(); // get the current time from the system
diff = expires_parsed_final - current_time ; // calculate the difference between the expires and current times.
// The following commented alert can be uncommented as a debugging tool
// alert("\n raw date " + '<%= session[:auto_session_expires_at] %>' +
// "\n exp parsed " + expires_parsed +
// "\n diff " + diff +
// "\n current_time " + current_time +
// "\n exp raw " + expires_raw +
// "\n exp date " + exp_date +
// "\n exp time " + exp_time +
// "\n exp tzh " + exp_tzh +
// "\n exp tzm " + exp_tzm +
// "\n exp par time " + expires_parsed_time +
// "\n exp par tm iso " + expires_parsed_time_iso +
// "\n exp par final " + expires_parsed_final);
if (diff < 180000) {
alert("\n Your Internal complaints session is about to timeout \n in less than 3 minutes \n \n " +
"Please save your work \n" +
"Navigating to any page will reset the timeout timer");
clearInterval(myVar); // this clears the current warning timer since the message has already been shown to the user.
}
}
// ------------------------------------ clearTimer ------------------------------------------
// When called, this function will stop the setInterval for myTimer so that we don't have
// multiple timers running
// ------------------------------------------------------------------------------------------
function clearTimer() {
clearInterval(myVar);
}
function myTest() {
alert("test inside the test");
}
<% end %>
One other problem I ran into was that Firefox and IE use a strict interpretation of the ISO standards for dates. That required a few extra steps to use the ISO 8601 format for the date before trying to date arithmetic in IE/FF.
This still needs a little work but perhaps it could help someone trying to do a similar 'prior to timeout' warning.

Related

GAS: Send automatically emails from spreadsheet with date ant time info

I've the following columns in a spreadsheet
email
name
link
date
time
file
subject
title
a.d#abc.com
Sam Z
abc
18.01.23
14:41:00
def
abc
Hello World
With following code deployed as add-on in google apps script console I want to autamtically send emails to certain adresses at certain date and time, I#ve activeted a trigger to run the app every minute, but somehow it does not work...any hint what could be wrong? I'm 100% sure it is connected with the right spreadsheet
function sendReminderEmails() {
var spreadsheet = SpreadsheetApp.openById("1h570Eb4IqAaAHciQzz0U9oY_uqGo9UDzpWtth78NkCY").getSheetByName("test");
var data = spreadsheet.getDataRange().getValues();
// console.log(data);
for (var i = 1; i < data.length; i++) {
var email = data[i][0];
var name = data[i][1];
var link = data[i][2];
var date = data[i][3];
var time = data[i][4];
var file = data[i][5];
var now = new Date();
if (now.toLocaleDateString() == date && now.toLocaleTimeString() == time) {
MailApp.sendEmail(email, "Reminder: " + file, "Hello " + name + ",\n\nThis is a reminder about the " + file + " at " + link + " on " + date + " at " + time + ".");
}
}
}
There are three problems with your code and the way you're approaching this problem:
The variables date and time that you got from the Sheet are Date objects, so you also have to call toLocaleDateString() and toLocaleTimeString() on them if you want to compare them with the now values.
Even if you correct the above, the value returned by toLocaleTimeString() is a time in the format HH:MM:SS XM so the trigger would have to run at the exact same second as the time in your Sheet, which is very unlikely. You would need to cut out the seconds to compare the exact minute.
Even if you correct the above and compare the exact minute, Apps Script's time-driven triggers are slightly randomized, so there's no guarantee either that the trigger will run every single minute, and there may be a gap of a few minutes between executions.
My suggestion is to instead try something like rounding down the times to the nearest 10-minute mark and set the trigger to run every minute to compare the times. You would also need an extra checkbox column to mark them as done and avoid sending multiple emails. It may look something like this example:
function sendReminderEmails() {
var spreadsheet = SpreadsheetApp.openById("1h570Eb4IqAaAHciQzz0U9oY_uqGo9UDzpWtth78NkCY").getSheetByName("test");
var data = spreadsheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
var email = data[i][0];
var name = data[i][1];
var link = data[i][2];
var date = data[i][3];
var time = data[i][4];
var file = data[i][5];
var checked = data[i][7];
var now = new Date();
var roundedtime = time.getHours() + ":" + Math.floor(time.getMinutes() / 10) * 10
var roundednow = now.getHours() + ":" + Math.floor(now.getMinutes() / 10) * 10
if (now.toLocaleDateString() == date.toLocaleDateString() && roundednow == roundedtime && !checked) {
MailApp.sendEmail(email, "Reminder: " + file, "Hello " + name + ",\n\nThis is a reminder about the " + file + " at " + link + " on " + date + " at " + time + ".");
spreadsheet.getRange(i + 1, 8).setValue(true)
}
}
}
The sheet would look like this:
In this case roundedtime and roundednow would cut off the seconds and round down the minutes so, something like 14:41:00 would become 14:40, so the email would be sent when the trigger fires at any time between 14:40 to 14:49, then the checkbox is selected with spreadsheet.getRange(i + 1, 8).setValue(true) so it won't send another email within the same timeframe. Most often the emails will be sent closer to the lower bound.
Another possibility could be to instead create the triggers programmatically by using the time in the Sheet. If you use a trigger to fire at a specific time it will run once and then expire, but there's a limit of 20 triggers / user / script, so you wouldn't be able to use this method with a lot of data. Either way, keep in mind that you'll need to sacrifice some accuracy if you want your current approach to work.

Difficulties with numeric date offset in luxon

Environment: Win 10 Pro, Chrome 85, luxon 1.25.0
What I am trying to achieve eventually is this: in an ASP.Net/c# application show to the user continuously the amount of time until a session time out will occur. Because server and client may be in different time zones I need the UTC offset of each. The client's offset is easy to get. To find the server's offset (with reference to the code snippet below): the server code puts the page last loaded time into lblLastLoaded. Object dto receives the parsed date parts, including dto.offset which, I gather, is supposed to be expressed in minutes. The subsequent call to luxon.DateTime.fromObject(dto) fails: pst is left undefined. When I do not set dto.offset (by commenting out 4 lines in the code below) pst gets the server time successfully, but without the offset; it appears that luxon uses the offset of my local system which is -7 hours.
<script>
function r4onload() {
// Get server time:
var st = document.getElementById('lblLastLoaded').innerHTML;
// Date Time Offset
// st has form YYYY/MM/dd HH:mm:ss -HH:mm
// 1 2
// 012345678901234567890123456
// For Example 2020/09/29 10:31:56 -07:00
let dto = {};
dto.year = Number(st.substring(0, 4));
dto.month = Number(st.substring(5, 7));
dto.day = Number(st.substring(8, 10));
dto.hour = Number(st.substring(11, 13));
dto.minute = Number(st.substring(14, 16));
var offsetHour = Number(st.substring(20, 23)); // works if these 4 lines are commented out
var offsetMinutes = Number(st.substring(24, 26)); // works if these 4 lines are commented out
dto.offset = offsetHour * 60 + Math.sign(offsetHour) * offsetMinutes; // works if these 4 lines are commented out
// dto.offset is correctly calculated to -420 minutes // works if these 4 lines are commented out
var pst = luxon.DateTime.fromObject(dto);
// pst is undefined at this point -- why??
// If I do not include anything about offset above (comment out the 4 lines
// containing offsetHours, offsetMinutes, and dto.Offset, then pst comes out like this:
// 2020-09-29T10:31:00.00000-07:00
// i.e., luxon used the offset -07:00 of my local system, not the one contained in variable st.
document.getElementById('Parsed').innerHTML = pst;
r4startTime();
}
function r4startTime() {
var dt = luxon.DateTime.local();
var h = dt.hour;
var m = dt.minute;
var s = dt.second;
m = r4checkTime(m);
s = r4checkTime(s);
document.getElementById('CurrTime').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(r4startTime, 2000);
}
function r4checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
A complete Visual Studio 2017 project DemoLuxon with the above code snippet in file Site.Master is here: https://1drv.ms/u/s!AvoFL8QrGVaTsQvbaB8-Zh7GdloV?e=ODjZW5
If the above approach is awkward, I would be grateful for suggestions of more elegant ways of determining the client/server offset difference.
I devised a workaround as follows below, but the original problem has not been answered:
<script>
function r4onload() {
var st = document.getElementById('lblLastLoaded').innerHTML;
// Date Time Offset
// st has form YYYY/MM/dd HH:mm:ss -HH:mm
// 1 2
// 012345678901234567890123456
// For Example 2020/09/29 10:31:56 -07:00
// Transform to ISO format:
st = st.substring(0, 4) + '-' + st.substring(5, 7) + '-' + st.substring(8, 10)
+ 'T' + st.substring(11, 19) + ".000" + st.substring(20);
document.getElementById('Xformed').innerHTML = st;
var pst = luxon.DateTime.fromISO(st, { setZone: true });
document.getElementById('Parsed').innerHTML = pst;
r4startTime();
}
function r4startTime() {
var dt = luxon.DateTime.local();
var h = dt.hour;
var m = dt.minute;
var s = dt.second;
m = r4checkTime(m);
s = r4checkTime(s);
document.getElementById('CurrTime').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(r4startTime, 2000);
}
function r4checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
i.e., put the date-time first into ISO format and then use luxon.DateTime.fromISO. Variable pst gets the correct date-time value including the offset. The problem with luxon.DateTime.fromObject with an offset remains unresolved.

Custom code to display current time not working

//<![CDATA[
var displayCurrentTime = new function() {
// Get values...
var sysHour = getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening = "AM"; // Initialize AM/PM notation
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins: getMinutes; // Get current minutes...
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(function() {
displayCurrentTime();
}, 1000);
//]]>
I've been reading up some information and I wanted to create a simple script that grabs the hour and minute, does some calculations to determine if it's AM or PM, creates a string variable from those results, and then slips it inside of a specific DIV element. It does this every second.
Most of the code I've written seems to make sense based on what I've read. In the beginning I've tried using function displayCurrentTime() {} as well as what you see below (var displayCurrentTime = new function() {}) and neither seem to work. I cannot get my text to display in the page. Note: the ID of the div is notificationBar, just as it is here.
Is there anything in this code that makes no sense, or does this actually warrant posting the full HTML?
You don't need new in front of function that you newly define, you don't instantiate class.
You have few syntax errors, like var curMins : ... instead of var curMins = ....
Also, you cannot use getHours() and getMinutes() methods, outside of Date object:
var displayCurrentTime = function() {
// Get values...
var d = new Date();
var sysHour = d.getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening = "AM"; // Initialize AM/PM notation
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins = d.getMinutes(); // Get current minutes...
var curSecs = d.getSeconds(); //optionally get seconds too
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + ":" + curSecs + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(function(){ displayCurrentTime(); }, 1000);
<div id='notificationBar'>
Time Here
</div>
See about Date object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
About functions and anonymous function expression:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#The_function_expression_(function_expression)
Also:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Howto
There are a few syntax errors in your function, I'll get to them one by one:
You shouldn't use new when declaring a function. Just drop it =) var displayCurrentTime = function() {
You are trying to assign a value to a variable using json syntax : in var minutes: getMinutes. You also forgot to execute the function, so try var minutes = getMinutes();
In (2) I assume you already declared the methods getHours and getMinutes, but if not, you can call them directly from a new Date object:
var date = new Date();
var sysHours = date.getHours();
var minutes = date.getMinutes();
//...
That should do it!
Extra: you can skip adding the displayCurrentTime to another function inside the setInterval function: window.setInterval(displayCurrentTime, 1000);
var displayCurrentTime = function() {
var date = new Date(); // Get current date object
var sysHour = date.getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening; // No need to initialize
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins = date.getMinutes(); // Get Minutes
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(displayCurrentTime, 1000);
<div id='notificationBar'></div>

How to change UTC hour (HH) to Local Time (HH)

We are accessing an API that allows us to schedule date/time. We need to check scheduled things so we do NOT double book on the same hour. The API is returning a time as just HH in military. However, it is using UTC HH. So if we schedule something at 1PM it is coming back 18.
I am trying to use Moment.js to change the UTC 18 back to CST (local time). I am failing horribly.
In the example below I am getting 18 from the API and my function below tries to turn to local time (happens to be CST). But the function is just converting or leaving it to 18. Help?
function changeTakenHoursFromUTC (taken) {
if(taken) {
for (var i = 0, len = taken.length; i < len; i++) {
// construct a moment object with UTC-based input
var utchour = taken[i].send_hour + ":00:00";
console.log( "Hour before change " + utchour);
var h = moment.utc(utchour);
// convert using the TZDB identifier for US Central time
h.tz('America/Chicago');
h.local();
console.log( "Hour before change " + h._i );
var s = h.format("HH");
taken[i].send_hour = s._i;
console.log( "Taken hour back in taken is " + taken[i].send_hour );
count += 1;
if(i == len-1 && count > 0) {
//
return;
}
} // end for
} // end IF
} // end changeTakenHoursFromUTC
you are just missing a format string in your moment.utc(utchour, "HH")
I created this function to kind of help as an example:
function changeTakenHoursFromUTC (taken) {
// construct a moment object with UTC-based input
console.log( "Hour before change " + taken);
var h = moment.utc(taken, "HH");
console.log(h.format("HH"));
h.local();
console.log( "Hour after change " + h.format("HH"));
}
changeTakenHoursFromUTC(18);

Check if time difference is less than 45 mins and run function - AngularJS

This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).
var date = new Date();
Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)
You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.
In full:
var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
// do something
}
You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:
var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');
However, this approach will fail if you're trying to compare time that cross over day boundaries.
Try this:
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
checkTime("14:10:00");
checkTime("16:30:00");
checkTime("17:10:00");
There's a JavaScript method called getMinutes(); you can use to get only the minutes and compare.
Your code should look something like:
var received_time = "14:10:00".split(':');
var minute = '';
if(received_time.length === 3) {
minute = parseInt(received_time[1], 10);
}
$scope.given_time = minute;
var the_time = new Date();
$scope.current_time = the_time.getMinutes();
And you now can do your thing:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Using a library like moment.js you can simply diff the two times.
var $log = $("#log");
/* Difference between just times */
$log.append("Difference between times\n");
var givenTime = moment("14:10:00", "HH:mm:ss");
var minutesPassed = moment("14:30:00", "HH:mm:ss").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
/* Better: Difference between times that have dates attached to them and cross a day boundary. */
$log.append("\n\nDifference between dates with times\n");
givenTime = moment("2015-12-03 23:33:00");
minutesPassed = moment("2015-12-04 00:14:00").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<p>Results:</p>
<hr>
<pre id="log"></pre>
<hr>
Caveat: If the given time is yesterday such as 11:30pm and the current time is 12:10am then you will get the wrong result. You'd want to use a date with the time if this type of thing is an issue for your use case.
The moment.js documentation
http://momentjs.com/docs/
Angular directive for moment documentation
https://github.com/urish/angular-moment/blob/master/README.md

Categories

Resources