Get NSDate from JSON? - 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.

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");

GOLANG json to Protoc with LocalDateTime, not DateTime

I'm working on a middleware using golang.
I'm consuming a REST-API which returns a Date in form of a LocalDateTime (e.g. "created": "2022-01-09T00:00:00",) and it should get mapped into an protoc message with the data class google/protobuf/timestamp.proto as we don't want to do the converting in the frontend. But apparently the timestamp.proto only supports DateTime with a timezone (so like that "created": "2022-01-09T00:00:00Z...") but as its an external API I'm consuming I cant change their datatype to DateTime. Does anyone know how to find and elegant solution without doing the complete mapping/unmashalling process manually?
That's the protoc message:
google.protobuf.Timestamp created = 7 [json_name = "created"];
That's the unmashaller we're using:
err = protojson.Unmarshal(body, protoMessageClass)
That's the error I'm getting:
ERROR: proto: (line ...): invalid google.protobuf.Timestamp value "2021-12-07T00:00:00""
First convert the time you receive as a string to a time.Time object:
t, err := time.Parse("2006-01-02T15:04:05", val)
Here "2006-01-02T15:04:05" represents the layout you expect.
Then you can use timestamppb built-in function to create a protobuf timestamp from a time.Time object:
tpb := timestamppb.New(t)
If you need the opposite, you can use AsTime from timestampb.Timestamp type and then format from time.Time object to make a string.

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

Realm format date JSON swift

I had JSON with a date "date_use" :
{"expense":
{"id":1,
"amount":123.3,
"date_use":"2015-07-04T00:00:00Z"}
}
I had an error on date format when I execute this code :
self.realm!.create(Expense.self, value:json["expense"].object, update: true)
Error :
Terminating app due to uncaught exception 'RLMException', reason:
'Invalid value '2015-07-04T00:00:00Z' for property 'date_use'
My question is : What is the good date format for Realm?
The problem here is not the particular date format, but that JSON doesn't support a native date type at all. So you have to serialize dates to a string format. Using RFC 3339, like you have to deal with, is generally a good choice because it avoids ambiguities, so you can stick with that.
Realm's create method doesn't expect deserialized JSON, but a dictionary representation of your object. This expects that you have done already the preprocessing step of transforming date string representations back to Cocoa's native type NSDate. This isn't done automatically because there are date formats, which are ambiguous (unlike yours), which e.g do not provide information about the timezone.
Good news is there are excellent third-party libraries e.g. Realm-JSON, which make it a whole lot easier to deal with that. It brings built-in support for that.
This would also allow to map the property naming scheme returned by your API, e.g. date_use to names which conforms to the more broadly used camel-case dateUse.
If you don't want to introduce another dependency just for that use case, you can use and configure NSDateFormatter to parse dates conforming to your particular subset of the RFC 3339 standard, assuming they always use UTC as timezone, marked through the Z suffix.
// Setup the RFC 3339 date formatter
let rfc3339DateFormatter = NSDateFormatter()
let enUSPOSIXLocale = NSLocale(localeIdentifier: "en_US_POSIX")
rfc3339DateFormatter.locale = enUSPOSIXLocale
rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
rfc3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
// Convert the RFC 3339 date time string to an NSDate
var json: AnyObject! = nil
var value = json["expense"] as! [String : AnyObject]
let date: NSDate?
if let dateString = value["date_use"] as? String {
date = rfc3339DateFormatter.dateFromString(dateString)
} else {
date = nil
}
value["date_use"] = date
// Create your object
self.realm!.create(Expense.self, value: value, update: true)

Marshalling Joda LocalTime in Grails

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