Appropriate JSON date format when sending from JSP to jQuery - json

As JSON format doesn't standardize dates subformat, this task is completely on a programmer, right?
When sending dates from PHP to Javascript and back I sent dates as a single integer in UNIX timestamp format (number of seconds since 01/01/1970).
On server:
$now = new DateTime('now');
$now->getTimestamp();
On client:
.success : function (data)
{
var date = new Date(data * 1000);
}
What's the best format for sending dates from JSP? (I'm JSP and Java newbie).
Obviously, it has to be easy encoding/decoding using Java native classes as well as Javascript Date object.
There should not be any problems with overflowing (I'm afraid after 2038 my PHP code will break).
Regards,

new Date(milliseconds) //milliseconds since 1970/01/01 - so you've solved your own problem. I personally prefer to use yyyy-mm-dd hh:ii:ss format as it readable and different from UK and US formats.

Related

Azure Logic Apps - Convert JSON Epoch Timestamp to DateTime String

I am working on an Azure Logic App that is triggered via an HTTP call and returns a JSON response. Internally, the logic app retrieves JSON data from a web API and then converts the response JSON data to a format that is acceptable to the calling client of the logic app.
The problem I'm having is that the web API is returning dates in the format "/Date(1616371200000)/" and I need the date format to look like "2021-03-32T19:00:00Z". I don't see any built-in logic app function that can work with or convert the Epoch timestamp as-is (unless I'm missing something).
To clarify...
Source Data:
{
"some_silly_date": "/Date(1616371200000)/"
}
Desired Data:
{
"some_silly_date": "2021-03-32T19:00:00Z"
}
The following solution would theoretically work if the source date wasn't wrapped with "/Date(...)/":
"#addToTime('1970-01-01T00:00:00Z', 1616371200000, 'Second')"
Parsing that text off the timestamp before converting it would lead to a really ugly expression. Is there a better way to convert the timestamp that I'm not aware of?
Note that using the Liquid JSON-to-JSON templates is not an option. I was using that and found this action apparently has to JIT compile before use which is causing my logic app to time-out when being called after a long period of inactivity.
Can you get the value "/Date(1616371200000)/" from the JSON into a variable? If so, a little string manipulation would do the trick:
int(replace(replace(variables('data_in'),'/Date(',''),')/',''))
Then use the variable in the addToTime function.
Result:
The following expression seems to be working and returns a timestamp in UTC. Note that the substring() function is only using a length of 10 instead of 13. I'm intentionally trimming-off the milliseconds from the Epoch timestamp because the addToTime() function only handles seconds.
{
"some_silly_date": "#addToTime('1970-01-01T00:00:00Z', int(substring(item()?['some_silly_date'],6,10)), 'Second')"
}
As an added bonus, if the timestamp value is null in the source JSON, do the following:
{
"some_silly_date": "#if(equals(item()?['some_silly_date'], null), null, addToTime('1970-01-01T00:00:00Z', int(substring(item()?['some_silly_date'],6,10)), 'Second'))"
}
Quite possibly the ugliest code I've ever written.

Converting date and time from response JSON in human readable format

The date and time in a response JSON looks like this:
2019-02-17T05:28:00
I tried to convert it with Regex to the following format:
17.02.2019 at 05:28:00
But failed.
let string = string
.split("T")
.join("")
.split("-")
.join("");
string = string.replace(
/(\d{4})(\d{2})(\d{2})(\d{8})/,
"$3$2$1$4"
);
What is the right way?
You can capture year month date and time in different groups using this regex,
(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})
And replace it with this,
$3.$2.$1 at $4
Demo
Javascript demo,
var s = "2019-02-17T05:28:00"
console.log(s.replace(/(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})/g,'$3.$2.$1 at $4'))
Your best bet is probably to use a date-time handling library such as Moment.js, which provides all sorts of nice date manipulation functionality.
You can then do things like
const moment = require("moment");
let formattedDate = moment.utc(isoDateVariable, moment.ISO_8601).format("DD/MM/YYYY");
It also helps you with all the general nastiness associated with dates and times in programs which you really don't want to be handling yourself.

Restkit JSON error parsing dates in range 1969/12/07 to 1970/01/25 GMT

Running Restkit 0.23 and iOS7.1.2 and iOS8gms when dates in range 1969/12/08 to 1970/01/25 GMT are encountered the parsing to JSON fails with an error: [datasource.table.values.property]: Parsing date N was not recognized as a date format... where N is a number of seconds.
I am unable to determine the JSON parser that is in use.
Restkit documentation refers to either YAJL or SBJSON being pluggable.
If someone can advise how to identify the parser in use and to change to another parser that would be much appreciated. Otherwise if anyone can advise an alternative resolution that would also be helpful.
This was a problem with the backend which is using FlexJSON and is a known feature of FlexJSON:
(http://sourceforge.net/p/flexjson/discussion/686321/thread/029d17be/).
Trying to use JSONDeserializer but Flexjson is having issues parsing the Unix TimeStamps into Date objects, only if the date is in the range of Dec. 7th, 1969 to Jan. 25th, 1970. All other dates outside of that range are parsed fine. The error that it's giving is: [JSONException: : Parsing date 21600000 was not recognized as a date format]
So no problem at all with the iOS native JSON parser which is what RestKit is using, RestKit is simply faithfully passing back the server error messages.

Json .net settings equivalent to JavaScriptSerializer default for dates

I am using the JQuery Ganntt plugin and it needs dates formatted in the Unix epoch format. Using Newtonsoft's Json.Net with these settings
JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};
return JsonConvert.SerializeObject(headers, microsoftDateFormatSettings);
I get json that looks like the following
[{"desc":"STAT","name":"Status","values":[{"to":"/Date(1357483427000-0500)/","from":"/Date(1354891427000-0500)/","desc":"","label":"Implement","customClass":"ganttBlue","dataObj":{"id":35,"projectId":18705,"updatedById":437996,"updatedByName":"Linda","updated":"/Date(1354891427000-0500)/","statusId":160,"statusDescription":"","status":"Implement"}}]},{"desc":"ASGNTO","name":"Assigned To","values":[{"to":"/Date(1357762454000-0500)/","from":"/Date(1355170454000-0500)/","desc":"Suzy","label":"Suzy","customClass":"ganttRed","dataObj":{"id":55,"projectId":18705,"updatedById":719816,"updatedByName":"Joe","updated":"/Date(1355170454000-0500)/","assignedToId":561260,"assignedToName":"Suzy"}}]}]
The gantt plugin does not like the date with the -500. It wants this, which is generated from using the JavaScriptSerializer
"[{\"desc\":\"STAT\",\"name\":\"Status\",\"values\":[{\"to\":\"\/Date(1357483427000)\/\",\"from\":\"\/Date(1354891427000)\/\",\"description\":\"\",\"label\":\"Implement\",\"customClass\":\"ganttBlue\",\"dataObj\":{\"Id\":35,\"ProjectId\":18705,\"UpdatedById\":437996,\"UpdatedByName\":\"Linda\",\"Updated\":\"\/Date(1354891427000)\/\",\"StatusId\":160,\"StatusDescription\":\"\",\"Status\":\"Implement\"}}]},{\"desc\":\"ASGNTO\",\"name\":\"Assigned To\",\"values\":[{\"to\":\"\/Date(1357762454000)\/\",\"from\":\"\/Date(1355170454000)\/\",\"description\":\"Suzy\",\"label\":\"Suzy\",\"customClass\":\"ganttRed\",\"dataObj\":{\"Id\":55,\"ProjectId\":18705,\"UpdatedById\":719816,\"UpdatedByName\":\"Joe\",\"Updated\":\"\/Date(1355170454000)\/\",\"AssignedToId\":561260,\"AssignedToName\":\"Suzy\"}}]}]"
What would be the proper setting for the Json.Net converter? I want to use Json.net when we move to .net 4.5.
To make it display a date that is like the one produced by JavaScriptSerializer, you have to give two settings:
JsonSerializerSettings serializerSettings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
Using any other type of DateTimeZoneHandling will cause the timezone offset to be put in. (Seems like a bug that Unspecified still puts the offset in.)
However, if you are using local time throughout the system, doing this will shift the dates by your timezone offset when serializing them. Your dates will be off.
The easiest fix for me was to use the default ISO date, set DateTimeZoneHandling to Local, and change the client to parse the ISO date. Otherwise you would need to adjust the dates before serializing or play with your own custom serializer. Neither of those last two seemed worth it to me.

Name of month serialized local specific

according to the coldfusion docs SerializeJSON converts Dates to strings which can easily be parsed by JavaScript Date objects.
I just serialized a query and JavaScript could not parse the Date columns because the name of the month was serialized local specfic returning Mai, what is not understood by JavaScript. Javascript only accepts english month names. Do I now - as I just did - have to replace the local specific month name manually with it's english translation to easily parse the string to a JavaScript Date object?
Best,
Bernhard
You could try and deal with this on the server by using setLocale('en_us') to force English language versions of your query when serialised - not ideal but it might get the job done. I think this can be set per request. See info here: http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7fa3.html
Hope that helps.
This answer to another question suggests that perhaps you could use datejs and then use the appropriate localization to parse your strings natively rather than in English.
I have a solution
In the coldfusion administrator add this -Duser.language=en -Duser.region=US to the JVM agruments. (And restart the service) You tell the JVM engine not to use the machine locale but to use the 'normal' english locale.
When you use SerializeJSON after the change it will generate dates with the enlish month names.
I haven't found any unwanted side effects with this change.