parseInt() sometimes returning NaN - google-apps-script

I'm trying to parse a DateItem response from a form so that it fits the form "M/D/YYYY" (ie 2014-08-05 would translate to 8/5/2014). Since the ItemResponse is of type String, I wrote the following to manipulate it:
s = s.replace(/(\d{0,4})\-(\d{0,2})\-(\d{0,4})/,'$2/$3/$1');
var arr = s.split('/');
return parseInt(arr[0]) + '/' + parseInt(arr[1]) + '/' + parseInt(arr[2]);
But parseInt(arr[0]) just randomly started returning NaN a couple days ago. arr[0] is not null when it comes time to parse, and it's of type string. Only that value in the array has the problem. I parseInt to remove the preceding 0 on single digits. Any thoughts?

Why does parseInt return NAN for "08" string and return 7 for "07" string?
Basically, a leading 0 indicates that it is a number in octal. 8 is not a valid octal digit, hence NaN. Use parseint(arr[0], 10) to specify the base. You'll probably want to do the same for arr[1].

You may want to use Utilities.formatDate(), this will return a formatted date string in a format of your choosing.
For your example:
var formattedDate = Utilities.formatDate(new Date(formDataDateValue), Session.getScriptTimeZone(), "M/d/yyyy");

Related

Dates are incorrect with json passed like "jsonObject.toString()"

I have a graph component written in javascript using the canvas. You can update its values if you pass it a valid json array, of dates, coupled with prices of that date (stock trading candlesticks).
The jsonArray I try to populate on this call usually comes from creating new dates in js - but is there a way to send my jsonArray down the wire (from Primefaces) in such a way that the dates get interpreted as dates?
When I use
PrimeFaces.current().executeScript("myFunction(" + jsonObject.toString() + ")");
Dates that come down the wire are becoming long looking numbers which I guess are the number of milliseconds since 1970. What can I do to send this (rather large) jsonarray and have its dates interpreted as dates? (they fail on the date.getMonth() call, because they are numbers instead of dates).
When creating the jsonArray on the server side, I do the following, which looks wrong because getTime() returns a long. So how would dates be properly handled here?
json.addProperty("date", data.getKey().getTs().getTime());
The function getting called with the long values as dates was the following. As Ultimater suggested, pass this object through new Date() - which should work for a date object - as well as a long, so no harm done!
dateToString(date, multiline) {
if(date === null)
return;
// Added this
date = new Date(date);
var datestr = date.getMonth() + " " + date.getDay() + ", " + date.getFullYear();

Can I pass a piped date as an argument? - Angular

Is it possible to pass a piped date as an argument for a function?
I am thinking of something along the lines of...
A variable date: string that will be assigned a value passed from a datepicker
The date picker currently outputs date values in the format:
Fri Feb 09 2018 00:00:00 GMT+0000 (GMT Standard Time)
It is possible to display the date in binding with use of date | date:'yyyy-MM-dd'
I am wanting to pass into a function, that piped date - something like:
someFunction(date | date:'yyyy-MM-dd');
Is there any way that this could be possible?
Or will I have to pass the original long date into a function, mutate it and then use it?
I have since found a way to just JS it - How do I get a date in YYYY-MM-DD format?
This splits the date and then recombines it into a string:
onSelect(theDate: Date): void {
var yyyy = theDate.getFullYear().toString();
var mm = (theDate.getMonth()+1).toString();
var dd = theDate.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
var dateString = yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
this.meetingService.getMeetingsByDate(dateString);
}

Ionic 2 JSON dates and moment.js trouble

I have a problem with dates manipulation with Ionic and moment.js.
I store some dates from a ion-datetime component :
{"year":2017,"month":7,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0}
And use moment.js to "humanize" date display :
let somedate = moment(some.date);
console.log('JSON date : ' + JSON.stringify(some.date) + ' resolved as : ' + somedate.format('DD/MM/YYYY'));
And got result :
Original JSON date : {"year":2017,"month":7,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0} resolved as : 26/08/2017
As you can consider, there's on month offset between original JSON date and moment display date...
What i'm missing ?
The Javascript month are in range of 0-11 i.e. January is 0, February is 1 and likewise, therefore it is moving you to the next month. Try subtracting 1 from month value, to get the correct month.
var some = {'date':{"year":2017,"month":6,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0} };
let somedate = moment(some.date);
console.log('JSON date : ' + JSON.stringify(some.date) + ' resolved as : ' + somedate.format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Finally, with your answers, i resolved the problem with a conversion method that take the original JSON date format and return a Javascript Date object, using TypeScript :
private _JSONDateToDate(jsonDate: any){
if(typeof jsonDate == 'object')
return new Date(jsonDate.year, (parseInt(jsonDate.month) - 1), jsonDate.day);
return jsonDate;
}
I substract 1 month of the "month" property in order to have a correct Date object... then, i can manipulate it with moment.js

Format JSON date before pushing into ko.observableArray

I am pushing Values into a ko.observalbeArray with an AJAX call,
I want to format the JSON return date to "YYYY-MM-DD" before I am pushing it into my observableArray.
The Specific element in my Code that I want to convert is: OrderTimeStamp: element.OrderTimeStamp
Here is an example of a date that gets returned from server:
/Date(1377200468203+0200)/
Here is my AJAX call:
$.ajax({
url: "/[URL TO API Method]/GetAllOrdersbyparm",
data: {Parm: ko.toJS(MyDataViewModel.SelectedParmater), Start: ko.toJS(MyDataViewModel.ParmStart), End: ko.toJS(MyDataViewModel.ParmEnd)},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
for (var i = 0; i < Result.d.length; i++) {
element = Result.d[i];
MyDataViewModel.OrderDetails.push({ OrderID: element.OrderID, OrderGUID: element.OrderGUID, OrderTimeStamp: element.OrderTimeStamp, OrderStatus: element.OrderStatus, QtyProductsOnOrder: element.QtyProductOnOrder, PaymentDate: element.PaymentDate });
}
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
So, this is an ASP.NET specific Microsoft Date "standard".
See
http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
why it should be avoided like the plague(1).
In that format the first component is a UTC milliseconds offset since the UNIX epoch.
The offset is TO local time, which is the opposite of the timezone offset in the JS Date string representations.
Use
var dateString = myDate.toJSON();
to serialize a JS Date object for sending.
Such a serialized datetime string, which is also in UTC (aka *Z*ulu), can be used to create a Date object thusly:
var myDate = new Date(dateString);
(1) In case you need to support this old ASP.NET Date format you can convert it to a proper JS Date like this (thanks [Roy Tinker][2]):
myDate = new Date(parseInt("/Date(1377200468203+0200)/".substr(6)));
I'm not familiar with that particular datetime notation.
Is that home-grown?
Is there documentation for that?
If not, then you are setting yourself up for trouble trying to interpret it.
That conversion toJSON would make it a UTC time and a few things are open for interpretation, unless documented in minute (no pun intended) detail.
So this is my answer: Be very sure you have the above definition in normative writing.
Now let me ramble on for a bit:
I went through that little exercise here...
http://en.wikipedia.org/wiki/ISO_8601 would be a good standard to base datetime notation on.
Now, you already get that format from the server, which looks like a millisecond time value since the epoch ('1970-01-01T00:00:00Z'), (probably with a timezone offset already applied to it!) combined with a timezone offset string in HHMM.
That's a bit scary, since those two components don't mix well.
Evaluated as an expression 1377200468203+0200 would subtract octal! 200 milliseconds! from 1377200468203. That's clearly not what's intended.
In ISO8601 (which this notation is not) this timezone offset would be FROM UTC, so the millisecond value would already have the 2 hour, 0 minutes offset applied to it.
Now the code could of course run on a machine which is in a different timezone than the datetime given.
The very crucial question is whether this millisecond datetime value has indeed the offset FROM UTC in it.
In that case, doing
var dt = new Date(1377200468203);
would be wrong.
If it is close to a daylight savings time switch time, it would be incorrect to just subtract to offset from it.
Note, not sure if below answers your question. If not, you may be helped by this one: How to format a JSON date?
Something along these lines should work:
var yyyy = element.OrderTimeStamp.getFullYear()
var mm = element.OrderTimeStamp.getMonth();
var dd = element.OrderTimeStamp.getDate();
var x = yyyy + '-' + (mm < 10 ? '0'+mm : mm) + '-' + (dd < 10 ? '0'+dd : dd)
element.OrderTimeStamp = x;
See this fiddle for an example. For reference, the MDN page has good documenation on Dates.
If you need more advanced date and time functionality I can recommend looking at MomentJS.

DateFormatting Error

I was trying to convert this format of String to Date and was unsuccessfull
"23-DEC-2008" to a Date Object ,it looks like its not accepting "-" and i could see NULL in the date object after formatting .
Can somebody let me know if u have come across this problem .
Thanks ,
Sudeep
The "-" shouldn't be an issue. I've converted SQL timestamp strings to Date objects with no problem (the format of SQL date strings is YYYY-MM-DD). What is the format string you're using? Try using the format string "DD-MMM-YYYY" and see if that works.
Edit
Sorry, my solution only applies to the DateFormatter class from Flex, and not Actionscript. After looking at the documentation for the Actionscript Date class I saw the following:
The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-). (1)
If you're stuck using straight Actionscript, it looks as if you'll have to write your own parse method that accepts the "-".
this sort of works ...
public function parse(source:String):Date {
var ret:Date = new Date(0, 0, 0, 0, 0, 0, 0);
var parts:Array = source.split("-");
ret.fullYear = Number(parts[2]);
ret.setDate(Number(parts[0]));
var month:int = "jan,feb,mar,apr,may,jun,jul,aug,sep,oct,now,dec".split(",").indexOf(String(parts[1]).toLowerCase());
if (month == -1) throw "could not parse month";
ret.setMonth(month);
return ret;
}
but really, i don't like it ... if 'DEC' were 'Dec' , then
Date.parse("23-Dec-2008".split("-").join(" "))
would work ... but still ... i think, you should get something more robust ...
greetz
back2dos