Converting and comparing DateTime which are in different formats - javascript

Currently I have an app that's making a rest call to the SharePoint api that gives me the last modified date, and then I am comparing that date to a date that I currently have stored as a tag in content control inside a word doc. Currently I am using the New Date() method to try and compare the two dates, however I am getting two different times. Both these date times are in UTC but formatted different.
The DateTime that I am getting from SharePoint is in this format: 2016-08-27T17:40:09Z
The DateTime stored in a Content Controls tag: 8/27/2016 5:40:09 PM
Current Code:
for (var x = 0; x < contentControls.items.length; x++) {
itemUrl = "https://*tenant*.sharepoint.com/sites/*site*/_api/web/Lists/GetByTitle('*list*')/items?select=Title,Title&$filter=Title eq '" + contentControls.items[x].title + "'";
$.ajax({
type: "GET",
async: false,
url: itemUrl,
headers: {
"Authorization": "Bearer " + sharepointToken,
"accept": "application/json;odata=verbose"
},
success: function (data) {
var sharepointDateTime = data.d.results[0].Modified;
var contentControlDateTime = contentControls.items[0].tag;
var test1 = new Date(sharepointDateTime);
var test2 = new Date(contentControlDateTime);
if (test1 != test2) {
// custom code
}
},
error: function (error) {
console.log("Fetching list from SharePoint failed.");
}
})
}
Desired Result
I would like to be able to compare two dates in my condition statement, and if they are different I am going I am going to do something inside my statement. VERY Important this can not be dependent on the users current time Zone. I am comparing UTC Time
Update
I have solved this by altering the api which is stamping the content controls. I am working in a time crunch so I could not really dwell much on this. What I saw was that the content control tags were not stamped with the time zone so it was comparing apples and oranges. However, I would like to leave this question open to see if some one can find a client side solution instead.

You are comparing object references of two date objects with each other using !=, not points of time. While the objects may represent the same point of time, the condition will always be true.
Instead you could compare the timestamps of the two dates as number values, which you can retrieve using valueOf():
test1.valueOf() != test2.valueOf()
Also note that the second date does not contain any time zone information, so it will be interpreted in the local time zone of the environment the code is executed in. This may lead to unexpected results.
You may want to look into Moment.js, which is the de-facto standard library for date handling in JavaScript and which offers a much more consistent and intuitive API for your use case.

Related

How can i fetch date in expressjs mysql?

I am trying to fetch the date value from a mysql server but when i printed the result;System gives an error.
In the code I can fetch the date value but when i printed it;It does not get printed correctly.(I tried to fetch a row with the value 2003-10-20 but i get 2003-10-19T21 when i printed it).
var dob_fetcher = "SELECT DOB_value FROM users WHERE Name_value='resname'";
var dob_fetcher_2 = dob_fetcher.replace("resname", req.session.name_session);
server.query(dob_fetcher_2, function (error, dob_result, fields) {
if (error) {
throw error;
} else {
var dob_value = JSON.stringify(dob_result[0]);
console.log(dob_result[0]);
}
});
JavaScript is adjusting for your local time zone which appears to be 3 hours behind UTC.
You can access the non time zone shifted values with the getUTC methods:
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCMonth()
Finally, you may want to consider a date library like Luxon which has a lot more options for handling time zones and formatting dates than what is built into JavaScript.

JavaScript, Google Sheets script - problem with date comparing

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()).

How can I 'fetchXml' records according to date but not time in CRM?

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();

Comparing Dates with AngularJS

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
//[...]
}

Issues with Date() when using JSON.stringify() and JSON.parse()

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.

Categories

Resources