I am building an AngularJS/Rails web app, part of it is creating bookings (function bookings) and in the dashboard I am trying to display two different tabs one with Current Bookings and one with Previous Bookings. the booking model has a function_date attribute and I am retrieving it from the API into a $scope.bookings array.
How to I compare dates (run an if statement on it) to do if function_data > today's date store it into CurrentBookings array if not store it into PreviousBookings array?
Hope that makes sense.
P.S. I am still teaching myself how to program so it might be a stupid question for some.
many way solved this problem but i am using to convert time in milliseconds then easy to compare.
var n = Date.now();
its give the current
Return the number of milliseconds since 1970/01/01:
1460260009358
First, try converting your string into a date. Then compare it to now.
var date = new Date('2030-03-30'); //this is a Date object
if (date > new Date()) { //Date object comparison
//[...]
}
// or
if (date.getTime() > Date.now()) { //unix timestamp (integer) comparison
//[...]
}
Related
I am new in Apps Script, and had never a chance previously to write in JavaScript.
So, I have a dataset in one sheet in Google about personal information of clients (ID, name, mail, contact). I have another dataset in another Sheet about clients payment (date of payment of the first installment, date of payment of the second installment and amount.
The last sheet that is in focus is the third one relating to unpaid bills.
Now, what I want is to copy columns about personal information from the first sheet into the third one. Here condition would be to copy only information about clients where difference between date of payment of the second installment and today() is greater than 45. Here is what I have tried:
function Neplacena2Novi() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheetFrom=ss.getSheetByName("Podaci o polaznicima"); //Data entry Sheet
var sheetTo=ss.getSheetByName("Neplaceni racuni"); //Data Sheet
var condition=ss.getSheetByName("Uplate novoupisani");
var range1=ss.getRangeByName("Prva rata");
var range2=ss.getRangeByName("Druga rata");
var startRow=3;
var endRow=ss.getLastRow();
function Neplacena2Novi(){
for var(i=startRow; i<(endRow+1)< i++) {
var startDate=new Date(condition.getRange(range1+1).getValue());
var endDate= new Date(condition.getRange(range2+1).getValues());
var difference=parseInt(endDate-startDate)/1000); //Dates are in format dd.mm.yyyy.
if(difference>45){
var values=sheetFrom.getRange(2, 1, sheetFrom.getLastRow(), 4).getValues();
sheetTo.getRange(3,1,1184,4).setValues(values);
}
}
var ui = SpreadsheetApp.getUi();
var potvrda = ui.alert("Odredili ste lica koja treba da se pozovu.");
}
function DugmeDodajKlijenta (){
var ui = SpreadsheetApp.getUi();
}
This code works but I didn't get anything in sheet! And I didn't now how to include today() function in formula for difference. But what I really want is to make a condition where difference would be today()-startDate().
Can someone please help me?
The code is not working because endDate is not a primitive value but a 2D array. Use Range.getValue() instead of Range.getValues(), like this:
const startDate = new Date(condition.getRange(row, startDateColumn).getValue());
const endDate = new Date(condition.getRange(row, endDateColumn).getValue());
...but that is not enough to make the code work. There is a syntactical error in the for loop line, and the i variable is not referenced in the loop. The whole thing is very inefficient because it reads and writes data row by row instead of doing just one read and just one write.
The new Date() calls are superfluous unless the "dates" in the spreadsheet are not numeric dates but text strings that just look like dates. The parseInt() call is also superfluous (plus, it is missing the radix parameter.)
JavaScript dates internally contain the number of milliseconds that have elapsed since 1 January 1970 0:00 UTC. To get the difference between two dates in days, try (endDate-startDate) / 1000 / 60 / 60 / 24. Note that there are many caveats — see Date.
The whole loop could be replaced with Range.getValues().filter(). It looks like the code should best be totally rewritten.
It is unclear why you would need a script in the first place, since the same can be done with a spreadsheet formula using e.g. filter() or query(). The personal info can be added to the missing payments data with a lookup e.g. arrayformula(vlookup()).
I query a dateTime object from PostgreSQL DB using an AJAX call which returns the following format:
2019-12-13T22:59:59Z // print type of: `undefined`
I now want to compare the timestamp of that object with the current time now and fire a function if the timestamp is not older than 5 seconds compared to the current time.
My idea is to calculate the difference in seconds and check the result for <> 5.
But how can I convert the database fetched dateTime object into a moment object to be able to compare them?
Edit:
Due to the conclusions from the comments provided, I changed my logic and end up with the following problem:
I have a timestamp in SQL which changes secondly. I fetch this timestamp with AJAX and would like to fire a function if the new timestamp is not older than 5 seconds than the previous one.
I set up moment.js objects to calculate the difference. Now my problem is that on the first iteration latestTick is not defined.
How can i design the loop that it compares both timestamps and always updates the latestTick with the lastTick for the next iteration (and also won't error on the first iteration)?
Javascript:
Ajax call...
[...]
lastTick = response[0].fields.account_lastTick.toString()
lastTick1 = lastTick.slice(0, 10)
lastTick2 = lastTick.slice(11, 19)
lastTick = lastTick1 + ' ' + lastTick2
lastTick = moment(lastTick, 'YYYY-MM-DD hh:mm:ss')
if ((lastTick.diff(latestTick, 'seconds')) != 0) {
console.log('not Zero')
} else {
console.log('Zero')
}
latestTick = moment(lastTick, 'YYYY-MM-DD hh:mm:ss')
[...]
To give you an idea on how to compare time in Moment.js. you can do this
import moment from "moment"
const dateTimeStr = "2019-12-13T22:59:59Z" // your DB already includes timezone in the response (UTC+00:00)
const dateTimeMoment = moment(dateTimeStr)
const next5MinsMoment = moment().add(5, 'minutes')
if(dateTimeMoment.isBefore(next5MinsMoment)) {
// fire function call
}
I am trying to sort firebase date by date but it is not working.
I have firebase data structure in this format
I use this function to call the node
var awardsref = CatalogueDB.ref("cageawards/" + mycagecode).orderByChild('Awarddate');
awardsref.on('value', Awardstable, errData);
this is the output
is there a work around to sort the data based on this date format?
As #GerardoHerrera pointed out, Firebase don't support sorting by Date. However, if you parse the dates and convert them to milliseconds based on the UNIX epoch, you should be able to sort them lexicographically according to that.
const date1 = new Date("04-07-2018").getTime();
date1; // 1523084400000
const date2 = new Date("06-02-2018").getTime();
date2; // 1527922800000
Since date1 is less than date2, it will sort as being before date2 in ascending order. Store those converted millisecond time values in your Firebase and you should be able to sort your dataset by them.
e.g.
"7MFD4" {
...
"SPE7L018P1428" {
"Awarddate": "04-07-2018",
"AwarddateMS": 1523084400000
...
}
...
}
Then do orderByChild('AwarddateMS').
According to the following page, How query data is ordered, a date is not considered in any sorting way. It first orders null values, then false values, then true, numbers, strings and finally objects.
And all sorting is made following a Lexicographical Order.
So you may need to do the sorting on the client side by your own methods.
There´s another post where you can find an explanation on how to sort by date here
I'm dealing with two entities, Appointments and Expenses. My goal is for a new Expense record to auto populate some its fields when the date of the expense is specified, onChange. It triggers a query that's supposed to return records that have the same date and owning user.
Here is my code:
function bringData()
{
var date = Xrm.Page.getAttribute("new_tripDate").getValue();
var owner = Xrm.Page.getAttribute("ownerid").getValue();
if (owner != null)
{
var ownerID = owner[0].id;
var ownerName = owner[0].name;
}
var fetchXml="<fetch mapping='logical'>"+"<entity name='appointment'>"+"<attribute name='regardingobjectid'/>"+"<filter>"+"<condition attribute = 'ownerid' operator='eq' value='"+ownerID+"' />"+"<condition attribute='scheduledstart' operator='on' value='"+date+"' />"+"</filter>"+"</entity>"+"</fetch>";
var retrievedAppointments = XrmServiceToolkit.Soap.Fetch(fetchXml);
if (retrievedAppointments.length == 0)
{
alert("No matching records were found.");
return;
}
else
{
console.log(retrievedAppointments);
}
}
It gets the date from the current Expense page and uses it for the query. However, the function gives me an error on change saying that the date "is invalid, or outside the supported range". I removed the date condition from the query and it returns records based on the owning user no problem. I figured the problem was that there is a specified time in the Appointment entity and not on the Expense date but I thought using the "on" condition operator would fix that issue. I'm at a loss.
Thanks
The date time format returned by Xrm.Page.getAttribute("new_tripDate").getValue() is something that fetch cannot handle, you need to convert it to an ISO Format at the bare minimum.
Change the date formatting by using ISOFormat method, or use a library like moment.js or come up with your own little helper function to return a properly formatted date string.
Replace your date variable with the following:
var date = new Date(Xrm.Page.getAttribute("new_tripDate").getValue()).toISOString();
I am trying to calculate the difference between two times using JavaScript. It's just basic math but I seem to have some issues with that while using JSON.stringify() and JSON.parse().
If you're wondering why am I applying the JSON.stringify() function to the date, it's because I using local storage to store some data on the client side and use it whenever the client lands on my website again ( it's faster that way rather than making more requests to the server ). That data usually updates once in a while ( I'm grabbing the data through API from another website ), so I set up a data_update variable and I'm storing it together with the other data.
That way I'm grabbing the stored data from the local storage and check if the difference between data_update ( which is a date / time ) and the time / date when the check it's made and see if it's greater than a week / day /etc .
So that is the reason why I'm using the JSON functions. My problem is that when I'm parsing the data from the local storage, the date seems to be different from a Date() object.
I'm trying to do the next operation per say :
var x = JSON.parse(JSON.stringify(new Date()));
var y = JSON.parse(this.get_local_storage_data(this.data_cache_key)); // the data object stored on local storage
var q = y.data_update; // this is the variable where the Date() was stored
console.log(Math.floor((x-q)/1000));
The above will return null. Also when I want to see the Math.floor(x) result, it returns null again.
So what can I do in this situation ? Is there a fix for this ?
If you look at the output of JSON.stringify for a Date, you'll see that:
JSON.stringify(new Date())
Results in a string. JSON does not have a primitive representation of Date objects that JSON.parse will turn back into a Date object automatically.
The Date object's constructor can take a date string, so you can turn those string values back into dates by doing:
var x = new Date(JSON.parse(JSON.stringify(new Date())));
Then the arithmetic will work.
x = new Date(JSON.parse(JSON.stringify(new Date())))
y = new Date(JSON.parse(JSON.stringify(new Date())))
y - x
=> 982
JSON.stringify(new Date())
returns
"2013-10-06T15:32:18.605Z"
Thank God is: Date.prototype.toISOString()
As the recommended answer suggests, the date is simply converted to a string when using JSON.stringify.
Another approach that would maybe fit this use case is to store the time in milliseconds using Date.now():
// Date.now() instead of new Date()
const millis = Date.now();
console.log(millis);
// same output as input
console.log(JSON.parse(JSON.stringify(millis)));
That way you can be sure that what goes into JSON.stringify comes out the same when using JSON.parse.
This also makes it easy to compare dates, if you have two millisecond values, using < and >.
Plus you can convert the milliseconds to a date at any time (usually before you render it to the user):
const millis = Date.now();
console.log(millis);
console.log(new Date(millis));
NOTE: using milliseconds as your date representation is usually not recommended, at least not in your database: https://stackoverflow.com/a/48974248/10551293.