Angular 5 not parsing timestamps correctly from json - json

I have a working (in production) web app (material + angular 5 (5.2.11)). Also I've an API written in .dot core 2 (C#) using Nancy FX and newtonsoft json.
Problem:
DB (mariaDB running on Ubuntu Server): I have this value: 2018-05-16 20:42:36 on a record.
Calling the endpoint yields the correct JSON:
{"timestamp":"2018-05-16T20:42:36Z"}
(the other fields were removed for sanity)
On Angular app I use:
... return this._http.get(this.endpoint + '/' + uuid, { headers:
this._getHeaders }).catch(this.handleError);
Where <T> represents a model that includes timedate: Date; as a property.
Using the service:
this._dataService.getByUuid(uuid).subscribe(result => {
console.log(result);
});
gives:
Object { timedate: "2018-05-16 08:05:36" }
So, the time lacks of AMPM format and I can't display it correctly. {{element.timedate | date: 'dd/MM/yyyy HH:mm' }} does nothing since timedate is just that, a bare string.
What have I tried:
Implementing a different format in JSON output (in NancFx API)
Adding a HTTP INTERCEPTOR
Reading this
Declaring the properties as Date, String
Problem is with any datetime field. The JSON is always on point and so the database.
Any help is appreciate

JSON doesn't have a Date type (only arrays, numbers, string, object, null and undefined), so the converter from JSON to TypeScript cannot know whether it's a date or a plain string.
You need to parse (Date.Parse(yourString) or new Date(yourString)) the Date property everytime your object is deserialized.
** Date.Parse and the Date constructor can take in a Date as well as a string so you don't really have to type check the value before using them.*

Related

How to type Date types with Prisma and JSON blobs?

There seems to be an issue with prisma's serialization of JSON blobs wrt Date types.
I wonder if anyone else has seen this and has some guidance/workaround.
This is for a JSON field with Planetscale which is basically MySQL driver.
I have an object with a Date field, that I want to encode. This is a blob of data coming back from an external API
eg my object tp has a field defined typed a Date:
trained_at: Date;
in my prisma schema for tunePrompt I have a JSON field:
model TunePrompt {
apiData Json? // from external API
But when I try to write to that apiData JSON field:
const data = {
apiData: tp,
}
const newPrompt = await prisma.tunePrompt.create({ data })
Property 'trained_at' is incompatible with index signature.
Type 'Date' is not assignable to type 'InputJsonValue | null | undefined'.",
if I were to do JSON.stringify(tp) this works without error, but then I get double escaped JSON.
The generated types are something like:
export type TunePromptCreateInput = {
apiData?: NullableJsonNullValueInput | InputJsonValue
}
the only workaround i've found is to type the Date fields as a string, but I'm sure this is going to lead to other parsing problems later.
Maybe I can look into typing the JSON blob, but I don't think that would solve the issue as its the serialization I think that's the problem.

how can I convert an object of type Any to a specific class type?

I am using Kotlin and I have a service that is getting an object of type Any (this cannot be changed)
The problem with Any is that is an object of 20+ fields and I just need one of them to use it as a filter... therefore I cannot do a simple cast.
So, my object is like: (when I print it)
{messageId=123, userId=32323, address=Some city, phone=111605,type=TYPE1.....
I want to convert it using Kotlinx or Jackson but I cannot convert it first to the expected String format, doing a parseFromString(myObject) will result in an exception as well of a wrong Json format.
I want to convert it to a class like this
#Serializable
private data class UserType(val type: String)
type is the only field I care about.
My convertion is via kotlinx
val format = Json { ignoreUnknownKeys = true }
format.decodeFromString<UserType>(myObject)
I even tried this to see if I can make it in the proper Json format
format.encodeToString(original)
Any idea what I could do here that would be a lightweight solution?
This is my Any type https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/

How can prevent dotnet core SignalR json serilizer from generate invalid json format

I create web-app with .net 5 and use SignalR for real-time communicate.
but when I send message to client with SendAsync() like this:
await _hubContext
.Clients
.Group(groupName)
.SendAsync(method, data, cancellationToken)
.ConfigureAwait(false);
Boolean value present in invalid JSON format false => False
and true => True.
Also string value present in single quote ' instead of double quote "
and null value present as None
So client side in python can parse result and convert to JSON object!
How can I prevent dotnet core SignalR JSON serilizer from generate invalid format result.
Thank.

Ballerina json datetime value

i have to index documents to elasticsearch to an index which has a date field mapping and i'm trying to build a json with this date value, but ballerina says this seems not possible.
I thought about storing this date value into an xml and after that to convert it to a json but xml has the same problem (i thought this might be a trick...).
I tried to store it into a string and after that to extract the json payload from that string but it gives me this error:
error: {ballerina/io}GenericError message=unrecognized token 'date=time=1591128342000'
I thought about dealing with this string to date conversion from inside elasticsearch but i would like to keep this scenario as the last one. I don't like it, beacause i have to do some queries based on timestamp after and storing date as a string would give me additional problems
So is there any way to trick ballerina in order to achive this json containing a date value ?
-----here is snapshot of the code giving me the error-----
It says:
incompatible types: expected 'json', found 'ballerina/time:Time'
JSON is a text format that is completely language independent (see e.g. json.org).
time:Time is a Ballerina language specific type JSON knows nothing about. Because there is no implicit conversion (for a good reason) one have to provide the conversion.
In this case you most likely want to convert time:Time to a ISO 8601 string presentation with time:toString.
The following code (Ballerina 1.2):
import ballerina/io;
import ballerina/time;
public function main() {
var btime = time:currentTime();
var j = <json> {
time: time:toString(btime)
};
io:println(j.toJsonString());
}
Correctly prints:
{"time":"2020-06-03T08:39:07.897+03:00"}
Maryam Ziyad has written a good introduction to Ballerina's JSON support.
The following code is updated for Ballerina Swan Lake Update 1 (2201.1.0) to show how to convert a Ballerina UTC time (time:Utc) to JSON representation. Note that it's also possible to use localized time (time:Civil) but that is no different from time to JSON conversion point of view.
One can read more about Ballerina time handling from the documentation of time module.
import ballerina/io;
import ballerina/time;
public function main() {
time:Utc now = time:utcNow(3);
json j = {
time: time:utcToString(now)
};
io:println(j.toJsonString());
}
That correctly prints:
{"time":"2022-07-20T06:03:46.078Z"}

ExtJS: which values does the Ext.picker.Date accept?

I have a datepicker in my form and it gets the value from the form.load in JSON format.
Which values does the datepicker support?
Because it won't bind this value:\/Date(1241215200000)\/.
I already have a convert function for the JSON format but I can't configure the field with a convert or renderer config.
convertDate = function (value) {
if (value == null) return null;
return new Date(parseInt(value.replace("/Date(", ""), 10));
};
The value have to be a valid JavaScript date or Ext.Date. So you should bind it like
new Date(1241215200000)
For example the Newtonsoft JSON serializer is capable of returning this for a given date. But if all fails you may consider overriding the setValue() of the picker and apply your converter there
Below is only valid for Ext.field.Date
(My first but wrong answer for a datepicker)
I recommend you to use the ISO 8601 date format for your dates. With that you need to set the submitFormat to c
submitFormat: 'c'
Tools like Newtonsoft.Json support the ISO 8601 date out of the box (and since .Net 4.5 release 1 as default).