Marshalling Joda LocalTime in Grails - json

I am trying to marshall an object that contains LocalTime joda type time. And the problem occurs if you try to return a time that is later than 12am, so in the example below if the start of a lesson is 14:00 (2pm) then the time is converted to 02:00 and not 14:00 in the specified format (hh:mm).
So my BootStrap.groovy file contains following code:
JSON.registerObjectMarshaller(Lesson) {
def returnArray = [:]
returnArray['start'] = it.start.toString("hh:mm")
return returnArray
}
Any idea how to fix it?
Thanks,

Well, to get a 24 hrs format you need HH:mm, that's why you get 02:00 instead of 14:00

Related

Unexpected (string, string, string) error when running the script

I'm running a script to generate a certificate and it runs through and creates the certificates becomes up with this error:
Error
Exception: The parameters (String,String,String) don't match the method signature for Utilities.formatDate.
createCertificates # Code.gs:51
The code in question that is in line 51 is:
empSlide.replaceAllText("<<Date>>", Utilities.formatDate(date, Session.getScriptTimeZone(), "dd, MMMM, yyyy"));
The method Utilities.formatDate(date, timeZone, format) requires the following parameters:
Name
Type
Description
date
Date
a Date to format as a String
timeZone
String
the output timezone of the result
format
String
a format per the SimpleDateFormat specification
In your scenario the first parameter is given as a String instead of a Date, and that generates the error. The variable date, as shown in line 51, is a string.
I am going to assume that you store the date in a string like "YEAR-MONTH-DAY", please correct me if I am wrong. In that case you can easily fix the script by calling the Date constructor like this:
var date = new Date("1994-11-30");

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"}

Angular 5 not parsing timestamps correctly from 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.*

Value of date object in a map is changed in a grails controller while using 'as JSON'

In my grails controller, i have set a value to a date object as :
def reportingTo = new Date("10/01/2013");
LinkedHashMap dynamicParams = new LinkedHashMap();
dynamicParams.put('reportingTo',reportingTo);
Now when i normally print the value of reportingTo as
println(dynamicParams);
Then the value is Tue Oct 01 00:00:00 NPT 2013 but when i print as json by doing:
println(dynamicParams as JSON);
Then the value becomes "2013-09-30T18:15:00Z".
How can i retrieve the same value as in earlier print i.e Tue Oct 01 00:00:00 NPT 2013.
I think the date has changed because of the change in timestamp. But cant figure out how.
Well you can change the JSON date format as you want you just need to set an ObjectMarshaller in BootStrap.groovy.
ObjectMarshallers : Simple Pogo/Pojo's that implement the
org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller
interface
Set it like below
import grails.converters.JSON;
class BootStrap {
def init = { servletContext ->
JSON.registerObjectMarshaller(Date) {
//use any format as you want
return it?.format("MM/dd/yyyy")
}
}
def destroy = {
}
}
Now if you want different format for different classes then you can create the different ObjectMarshaller and register them under the Bootstrap.groovy
Gregg has given an quite good explanation for the same you can find it over ->
How to set date format for JSON converter in Grails

Get NSDate from JSON?

I am working with Openweather API and trying to parse date property from JSON. This is date format: "dt" - Time of data calculation, unix, UTC. I have Forecast struct and there i've var date: NSDate. In weatherManager.swift i am working with SwiftyJSON and i tried with let date = json["dt"].double and other extension but it won't work.
Any suggestion? Thanks
If the date inside the API response is Unix timestamp, that means that you have to convert it to NSDate object. Since the unix time timestamp is number of seconds (in OpenWeather API) elapsed from 1. January 1970, we can use NSDate(timeIntervalSince1970:) method to convert it to NSDate object that you need.
let dateUnix = json["dt"].double
let date = NSDate(timeIntervalSince1970: dateUnix)
date object is now NSDate that you need.