Date.now() returning NaN in PhoneGap - date

I can't seem to get the timestamp in my phonegap application. A simple call to Date.now(), e.g. the following, results in NaN.
console.log("lastEditedOn: " + Date.now().toString() );
LogCat:
01-26 18:28:59.997: I/Web Console(17970): LastEditedOn: NaN:220
Can anyone see what I am doing wrong?
Cheers,
Don

Managed to get the correct timestamp with this:
var d = new Date();
var lastEditedOn;
lastEditedOn = d.getTime();
console.log(lastEditedOn);
Cheers,
Don

You cannot directly toString the Date.now() because it returns the milliseconds from midnight, Jan 1 1970.
You need to convert them like this:
function printDate() {
var temp = new Date();
var dateStr = padStr(temp.getFullYear()) +
padStr(1 + temp.getMonth()) +
padStr(temp.getDate()) +
padStr(temp.getHours()) +
padStr(temp.getMinutes()) +
padStr(temp.getSeconds());
debug (dateStr );
}
function padStr(i) {
return (i < 10) ? "0" + i : "" + i;
}

Related

Comparing Dates in Google Scripts with Sheets Input

I am trying to create a pop up to warn a user they must update a part in inventory if the part date is more than 90 days old. The date on the sheet (Cell Q5) is autofilled from another sheet, but that shouldn't matter. The value for the cell on the spreadsheet is 9/2/2021. I've tried many things, but currently I am getting the value for Q5 showing up as NaN .
function CheckInvDate() {
var ss = SpreadsheetApp.getActive().getId();
var partsrange = Sheets.Spreadsheets.Values.get(ss, "BOM!A5:Q5");
var currentDate = new Date();
var parthist = new Date();
parthist.setDate(currentDate.getDate() -90);
for (var i = 0; i < partsrange.values.length; i++){
var name = partsrange.values [i][1]
var partdate = partsrange.values [i][16]
var parthisttime = new Date(parthist).getTime();
var partdatetime = new Date(partdate).getTime();
Logger.log("History " + parthisttime)
Logger.log("Current " + partdatetime)
SpreadsheetApp.flush()
// if (parthist > partdate == "TRUE") {
// SpreadsheetApp.getUi().alert('The price on '+ name + ' is out of date. Please update price and try again.')
// }
}
}
My last log was
[22-07-06 11:50:55:851 EDT] History 1649346655850
[22-07-06 11:50:55:853 EDT] Current NaN
I've seen a number of responses on Stack Overflow, but I can't understand them. They seem to refer to variables that I don't see in code, or commands I haven't seen before and I'm not sure if they are in date.
Try this:
function CheckInvDate() {
const ss = SpreadsheetApp.getActive();
const vs = Sheets.Spreadsheets.Values.get(ss.getId(), "BOM!A5:Q5").values;
let d = new Date();
d.setDate(d.getDate() - 90)
const dv = d.valueOf();
const oldthan5 = vs.map(r => {
if (new Date(r[16]).valueOf() < dv) {
return r;
}
}).filter(e => e);
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(`<textarea rows="12" cols="100">${JSON.stringify(oldthan5)}</textarea>`).setWidth(1000), "Older Than 90 Days");
}
This outputs a dialog with the rows older than 90 days
I went to try this on my script again after lunch, and for whatever reason I am no longer getting the NaN value. I made one change on the if statement to fix the logic, and now it is working correctly. Not sure what I did, but apparently the coding gods were unhappy with me before.
The only part I changed was
if (parthisttime > partdatetime) {
SpreadsheetApp.getUi().alert('The price on '+ name + ' is out of date. Please update price and try again.')
}

Google Calendar API returning generic Bad Request

I'm currently struggling with figuring out what's wrong with a Event insert I'm trying to accomplish in Flutter using Google Calendar V3 API. Initially I thought it's a matter of RFC3339 vs ISO8601 date formats, but I'm grasping at straws.
Unhandled Exception: DetailedApiRequestError(status: 400, message: Bad Request) is what I'm getting from:
import 'package:googleapis/calendar/v3.dart';
import 'package:googleapis_auth/auth.dart';
import 'package:googleapis_auth/auth_io.dart';
...
var calendar = await getCalendar();
var ac = await getOrCreateCredentials();
var client = await getClient(ac);
var calendarId = await storage.read(key: "calendar_id");
var capi = CalendarApi(client);
EventCreator ec = new EventCreator();
ec.displayName = "Display Name";
EventDateTime edt = new EventDateTime();
int hour = int.parse(ds.hour.split(":")[0]);
int min = int.parse(ds.hour.split(":")[1]);
DateTime x = ds.data.add(Duration(hours: hour, minutes: min));
edt.dateTime = x;
edt.timeZone = x.timeZoneName;
EventDateTime edtEnd = new EventDateTime();
DateTime y = x.add(Duration(hours: 1));
edtEnd.dateTime = y;
edtEnd.timeZone = y.timeZoneName;
Event e = new Event();
e.created = DateTime.now();
e.creator = ec;
e.description = d.var + " \n" + d.var;
e.summary = "Summary";
e.etag = d.var;
e.location = d.var;
e.start = edt;
e.end = edtEnd;
try {
capi.events.insert(e, calendarId);
The full JSON response contains nothing else except global domain, badrequest and HTTP 400 code.
I also tried .toUtc() on the DateTime objects to make them RFC3339 compliant, but still the same error presents.
Later Edit
The issue is indeed related to the time, the Dart DateTime class does not format the time in a way Google likes (2021-04-12T08:30:00+03:00 which I've deduced from other languages' API implementations, and the source code of the package which does a .toString() of the DateTime basically).
The way around this is to create the EventDateTime from a JSON object, and to use a hacky Dart extension. I apologize for the naming but it's annoying.
extension FuckyDateTime on DateTime {
Map<dynamic, dynamic> fuckyDateTime() {
Map<dynamic, dynamic> x = new Map();
String formatted = this.year.toString() +
'-' +
(this.month.toString().length == 1
? '0' + this.month.toString()
: this.month.toString()) +
'-' +
(this.day.toString().length == 1
? '0' + this.day.toString()
: this.day.toString()) +
'T' +
(this.hour.toString().length == 1
? '0' + this.hour.toString()
: this.hour.toString()) +
':' +
(this.minute.toString().length == 1
? '0' + this.minute.toString()
: this.minute.toString()) +
':' +
(this.second.toString().length == 1
? '0' + this.second.toString()
: this.second.toString()) +
'+' +
'03:00';
x.putIfAbsent('dateTime', () => formatted);
x.putIfAbsent('timeZone', () => 'Europe/Bucharest');
return x;
}
}
and EventDateTime edt = new EventDateTime.fromJson(x.fuckyDateTime()); where x is a DateTime object.
The issue is indeed related to the time, the Dart DateTime class does not format the time in a way Google likes (2021-04-12T08:30:00+03:00 which I've deduced from other languages' API implementations, and the source code of the package which does a .toString() of the DateTime basically). Fair mention that Dart DateTime does provide a String of ISO8601, Google wants an RFC3339 compliant date.
The way around this is to create the EventDateTime from a JSON object, and to use a hacky Dart extension. I apologize for the naming but it's annoying.
extension FuckyDateTime on DateTime {
Map<dynamic, dynamic> fuckyDateTime() {
Map<dynamic, dynamic> x = new Map();
String formatted = this.year.toString() +
'-' +
(this.month.toString().length == 1
? '0' + this.month.toString()
: this.month.toString()) +
'-' +
(this.day.toString().length == 1
? '0' + this.day.toString()
: this.day.toString()) +
'T' +
(this.hour.toString().length == 1
? '0' + this.hour.toString()
: this.hour.toString()) +
':' +
(this.minute.toString().length == 1
? '0' + this.minute.toString()
: this.minute.toString()) +
':' +
(this.second.toString().length == 1
? '0' + this.second.toString()
: this.second.toString()) +
'+' +
'03:00';
x.putIfAbsent('dateTime', () => formatted);
x.putIfAbsent('timeZone', () => 'Europe/Bucharest');
return x;
}
}
and EventDateTime edt = new EventDateTime.fromJson(x.fuckyDateTime()); where x is a DateTime object.

How to test a Angular js date picker from Protractor

I'm new to Protractor and here I'm trying to test an angularjs date picker from Protractor.
I tried to find a way to do this and this article was the only thing I found and It is not very clear to use
If someone know how to test please help.
What I need is to select today's date.
Thanks in advance :)
edit -
alecxe, here is the screen shot of my date picker. Unfortunately cannot provide the link of the page. :(
<input
class="form-control ng-pristine ng-valid ng-not-empty ng-touched"
ng-model="invoice.fromdate"
data-date-format="yyyy-MM-dd"
data-date-type="string"
data-max-="" data-autoclose="1"
bs-datepicker=""
ng-change="dateRange()"
type="text">
I think you can avoid manipulating the datepicker manually and instead set the date either by just sending the keys with a today's date value:
var picker = element(by.model("invoice.fromdate"));
// get today's date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
picker.clear();
picker.sendKeys(today);
Or, by setting the associated model's value directly:
picker.evaluate("invoice.fromdate= '" + today + "'");
Two methods have been suggested so far: 1. sendKeys() 2. evaluate()
I'm a bit new to protractor but I think both of these have issues in the case of not having an input element that spawns the calendar, i.e.:
Sendkeys() works only if date is on an element and the uib-datepicker is a dropdown sort of deal. This didn't help me because my datepicker element is a standalone and isn't paired with an input element.
evaluate() doesn't update angular's actual model in the browser (which begs the question of how useful evaluate actually is...). According protractor docs, evaluate, "Evaluates the input as if it were on the scope of the current underlying elements." In my case I want to test whether the date generated by the datepicker gets to my enpdpoint via a post request and then back again (hence e2e) without getting effed (corrupted), therefore, I need my date to be on my angular model in the browser instance, not just in the browser-driver environment or whatever the runtime environment of the protractor test is. I could be wrong about this.
This expect() passes but the ng-form is invalid (i'm assuming b/c model in browser wan't actually updated to receive the date I'm trying to pass in.):
function convertToPickerDate(date) {
var date = new Date(date);
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
var yy = yyyy.toString().slice(2);
return mm + '/' + dd + '/' + yy;
}
// expect passes, but form is invalid - DON'T USE for standalone cal
it('should enter start date in date picker', function () {
offerStart = convertToPickerDate(myData.startDate);
var offerStartPicker = element(by.model('current.startDate'));
offerStartPicker.evaluate("current.startDate = '" + offerStart + "'");
offerStartPicker.evaluate("current.startDate").then(function (value) {
expect(value).toBe(offerStart);
});
})
but the ng-form that the element is on is invalid...
My solution uses css selection and arrow keys to select a date relative to today:
Shipment Start Date: <em id="offerStartPrint">{{current.startDate | date:'shortDate' }}</em>
<div id="offerStart"
name="offerStart"
uib-datepicker
ng-model="current.startDate"
class=""
ng-change="setStartDate()"
datepicker-options="startDateOptions"
required></div>
</div>
function convertToPickerDate(date) {
var date = new Date(date);
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
var yy = yyyy.toString().slice(2);
return mm + '/' + dd + '/' + yy;
}
it('should enter expiration date in date picker using tabs and arrows :)', function () {
// select today element on uib-datepicker calendar
// div#offerStart elem has date model
var calToday = element(by.css('div#offerStart table td button.active'));
calToday.sendKeys(protractor.Key.ARROW_DOWN); // one week away
calToday.sendKeys(protractor.Key.ARROW_DOWN); // two weeks away
calToday.click(); // if you remove this click no date is entered
var fortnightAway = new Date(Date.now() + 12096e5);
fortnightAwayString = convertToPickerDate(fortnightAway);
expect(element(by.id('offerStartPrint')).getText()).toBe(fortnightAwayString);
})
Left and right arrows can be used to increment/decrement date by one day at a time.
up/down arrows can be used to inc/dec one week at a time.
One could probably figure out how to arrow through months and years as well.
var data_picker = element(by.model("invoice.fromdate"));
// select current date with date function
var current_date = new Date();
var day = today.getDate();
var month = today.getMonth()+1; //By default January count as 0
var year = today.getFullYear();
if(day<10) {
day='0'+day
}
if(month<10) {
month='0'+month
}
current_date = month+'/'+day+'/'+year;
data_picker.clear(); // Note if you are facing error message related to clear. Comment this line
data_picker.sendKeys(today);
Hope this will work

Google maps downloadUrl does not return 200

My code is based on the example of google code:
https://developers.google.com/maps/articles/phpsqlinfo_v3
and was working fine.
I need to change a former 'gid' (Integer) field to 'id' (String) to get saved to the database and used to display a new labeled symbol on the map.
The strange thing is, that the url, that is build in the code to call the addrow.php file is OK. When I capture this string with alert(url), and I manually use this string, the new data is added to the database.
In my script, the call seems to fail (responseCode == 200 && data.length <=1), since no data is written to the database and the alert from the 'else-clause' is displayed as short pop-up.
Here's the code I use in my project (to save data from a form):
//save new marker to Postgis-database and add new markerwithlabel on the fly
function saveData(){
var gender = escape(document.getElementById("gender").value);
var hoehe = InZahl(document.getElementById("hoehe").value);
var breite = InZahl(document.getElementById("breite").value);
var id = escape(document.getElementById("id").value);
var vital = document.getElementById("vital").value;
var typ = document.getElementById("typ").value;
var ein_mehr = document.getElementById("ein_mehr").value;
var st_durchm = document.getElementById("st_durchm").value;
var frucht = document.getElementById("frucht").value;
var anmerk = document.getElementById("anmerk").value;
var latlng = marker.getPosition();
var url = "./mapdata/addrow.php?gender=" + gender +
"&hoehe=" + hoehe + "&lat=" + latlng.lat() + "&lng=" + latlng.lng() +
"&breite=" + breite + "&id=" + id + "&typ=" + typ + "&ein_mehr=" +ein_mehr + "&st_durchm=" + st_durchm +
"&frucht=" + frucht +
"&vital=" + vital + "&anmerk=" + anmerk;
downloadUrl(url, function (data, responseCode) {
if (responseCode == 200 && data.length <=1) {
infowindow.close();
marker.setDraggable(false);
marker.setIcon('./images/mm_purple.png');
marker.labelContent = id;
marker.setMap(map);
downloadUrl("./mapdata/getxml_get_last.php", function (data1) {
var xml = parseXml(data1);
var ms = xml.documentElement.getElementsByTagName("m");
var gid = ms[0].getAttribute("gid");
var html_n = "<div id='InfoWindow'><p style='font-weight:bold;'>" + id + "</p> \n\<p>Höhe:" + hoehe + " Breite: "+ breite +
"<br />\n\Typ: "+typ+" Stämme: "+ein_mehr+" St-Durchm: "+ st_durchm + "<br />\n\Vitalität: "+vital+" Fruchtbehang: "+frucht+
"<p/>\n\<p style='text-align:right;'><a href='sm_juniperus.php?operation=ssearch&ResetFilter=0&SearchField=gid&FilterType=%3D&FilterText="+ gid +
"' target='_blank'> Daten editieren </a></p></div>";
infowindow.setContent(html_n);
bindInfoWindow(marker, map, infowindow, html_n);
(function(i, marker, gid) {
var origIcon = marker.getIcon();
new LongPress(marker, 1000);
google.maps.event.addListener(marker, 'longpress', function(e) {
marker.setDraggable(true);
marker.setIcon(mmcross);
});
google.maps.event.addListener(marker, 'dragend', function(){
updatePosition(marker, gid);
marker.setIcon(origIcon);
});
})(i,marker,gid);
//add new marker to markerCluster-Array and to markerArray
markerCluster.addMarker(marker,false);
markerArray.push(marker);
i++;
}); // End add new marker
}
else {
alert("Your data couldn't be saved!");
}
}); // End downloadUrl
}; // END saveData()
As I said, my code worked fine, but after 3 evenings passed to solve this, I thought it would be time to ask for help.
If anybody has an idea, where the mistake lies, I would apreciate any hint.
Just to confirm, you're aware that you by doing
if (responseCode == 200 && data.length <=1) {
you are saying 'if the request is successful and the data it returns is only one character or below in length'? I am unsure if this is intended or not, because this way the code inside the if statement is only ran if the response is successful but contains only 1 or 0 characters.

Parse query to print all results in a given time frame

I would like to create a query that will allow a user to type in a starting date, and print out all records of a table from that date until the current time. I keep getting "Error 102: invalid field type for find". Any suggestions?
function billingReport(){
startDate = new Date(document.getElementById("startDate").value);
var caseList = Parse.Object.extend("Cases");
var query = new Parse.Query(caseList);
query.greaterThanOrEqualTo("createdAt", "startDate");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " scores.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('playerName'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
mentioned in a comment above, but I just wanted to end this topic correctly. The two date objects were of different types, so i added .toISOString to the startDate object and it worked like a charm