Usually I get dates like 2017-02-25T06:36:21.530
And I use the following annotations:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
#JsonSerialize(using = LocalDateTimeSerializer.class)
#JsonDeserialize(using = LocalDateTimeDeserializer.class)
#JsonProperty
However this fails if the time provided has no milliseconds e.g. 2017-02-25T06:36:21
Is there a way to specify to just ignore milliseconds in this case use 000 for instance?
Thanks, Jason
Not sure why you use the custom deserializer, but for doing this kind of deserialization you don't need it, as well as the #JsonFormat.
You can just configure the mapper and will work with the dates in that format (iso 8601), even without milliseconds:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// In case you use Java 8 dates
mapper.registerModule(new JavaTimeModule());
Related
I have run into an issue using attempting to add values from two different columns together in a query, namely that some of them contain numbers. This means that the built in Concat does not work as it requires strings or chars.
Considering how one can cast variables as other datatypes in SQL I don't see why I wouldn't be able to do that in Django.
cast(name as varchar(100))
I would assume that one would do it as follows in Django using the Concat function in combination with Cast.
queryset.annotate(new_col=Concat('existing_text_col', Cast('existing_integer_col', TextField())).get())
The above obviously does not work, so does anyone know how to actually do this?
The use case if anyone wonders are sending jenkins urls saved as fragments as a whole. So one url would be:
base_url: www.something.com/
url_fragment: name/
url_number: 123456
I ended up writing a serializer that inherits from the base serializer that contains the urls fragments and a lot of other things. In it I made a MethodField for my complete url and defined a getter function that loaded in the different fragments and added them together. I also redeclared the fragmented fields to None.
The code inside the new serializer is:
complete = serpy.MethodField("get_copmlete")
serverUrl = serpy.Field(attr=None, call=False, required=False)
jobName = serpy.Field(attr=None, call=False, required=False)
buildNumber = serpy.Field(attr=None, call=False, required=False)
def get_complete(self, obj):
return obj.server_url + obj.job_name + '/' + str(obj.build_number)
I have a database with measured values from devices that I want to display in a web frontend. First I send the list of devices to the frontend together with the IANA timezone specifier for each device.
I would like all timestamps to be exchanged as UTC. The user selects a time range in the frontend in device-local time. I use moment.js to convert these timestamps to UTC with the known timezone of the device like this:
var startTimestamp = new Date(2017, 7, 1); //some local timestamp (zero-based month!)
var m = moment.tz(startTimestamp, "Europe/Berlin");
var utc = moment.utc(m).format();
utc is now "2017-07-31T22:00:00Z" which seems to be correct given the 2 hours offset for Berlin in DST.
I send this utc timestamp to my ASP.NET Core backend. The controller looks like this:
[HttpGet]
public IEnumerable<TimestampedValue> GetValues(int id, DateTime startTimestamp)
{
...
}
The problem is that startTimestamp is 2017-08-01 00:00:00 when the controller is called and its Kind property is set to Local. I would have expected it to be the same UTC timestamp.
Any idea what I'm doing wrong? I think moment.js is doing its job correctly so this must be a problem on the server side. If I recall correctly, the deserialization is done by JSON.net but I don't understand why it does not respect the Z at the end of the time string.
After #dbc pointed me to the different behavior between GET and POST requests I come to this conclusion:
Since my request uses the GET method and query strings are not JSON, there is no JSON.net involved in the problem, it is the default .NET Core DateTimeConverter that does the conversion. Moment.js correctly converts the timestamp to a UTC string, I checked that using the browser developer tools.
The code for DateTimeConverter can be found here:
https://github.com/dotnet/corefx/blob/312736914d4e98c2948778bacac029aa831dd6b5/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeConverter.cs
As can be seen there, the converter uses DateTime.Parse. It can be tested in a simple test project that DateTime.Parse does not respect the Z-suffix. This is also discussed here DateTimeConverter converting from UTC string.
I think there would be at least four solutions
1) write a custom model binder. These SOs each show a part of it Custom DateTime model binder in ASP.NET Core 1 (RTM)
https://dotnetcoretutorials.com/2016/12/28/custom-model-binders-asp-net-core/
2) write a custom type converter that overrides the default DateTime converter and checks whether there is a trailing Z. If so, use DateTime.Parse with the DateTimeStyles.AdjustToUniversal. Else fall back to the default implementation. I like this solution but I currently don't know how to replace the default DateTimeConverter.
3) replace all relevant DateTime parameters in the controllers with DateTimeOffset. DateTimeOffset seems to correctly convert the UTC string.
4) use a POST instead of a GET request with JSON in the request body. JSON.net seems to correctly convert the UTC string.
My preferred solution is currently a mixture of 3 and 4, depending on the context.
I am struggling a bit trying to generate some JSON from a query I execute. All of the groovy JsonBuilder examples I've looked at only seem to deal with statically defining a dataset.
code:
def db = new Sql(datasource)
def builder = new JsonBuilder()
db.eachRow('SELECT t.day, t.start FROM mytable') { row ->
builder.days {
day(
date row.day
)
}
}
println builder.toString()
I had it at 1 point where it was printing only the last value in the resultset out.
Currently I am receiving the following error:
unexpected token: $ # line 46, column 18.
date row.day
I'm still a bit of a novice at groovy, any help greatly appreciated.
I generally prefer to present JsonBuilder with a complete object rather than use the DSL, so my solution would look something like this:
def map = [days:[]]
def db = new Sql(dataSource)
db.eachRow('SELECT t.day, t.start FROM mytable') { row ->
map.days << [day : [date: row.day]]
}
println new JsonBuilder(map).toString()
If you have a large number of results, this approach has the advantage of not forcing you to compile a huge list of GroovyRowResult objects, only a huge list of much smaller LinkedHashMap objects.
The builder there does not opening a list, add items, then close it. you would have to provide it in a single go. E.g. collect all rows as maps:
def builder = new groovy.json.JsonBuilder()
def dbresult = [1,2,3]
builder {
days dbresult.collect{
[day: [date: it]]
}
}
println builder
Use db.rows to get the list. You might have to try, what is happening, if you just send in the result. Maybe needs a cast to a Map or you have to do the mapping yourself.
If your rowcount is very high, you might be better off some other library, that don't need you to manifest the list beforehand.
I have the following code:
sql.eachRow(sqlQuery, ((pageNumber-1)*pageSize)+1, pageSize) { row ->
List<String> nextRow = new ArrayList<String>();
nextRow.add("$row.EVENT_TMSTP");
...
but what I get for the timestamp is:
oracle.sql.TIMESTAMP#1d44e01
instead of:
12-SEP-13 10.55.00.392000000 AM
I've tried various ways to get the timestamp formatted, but none work. Can anyone help?
According to the documentation, you should just be able to call:
nextRow.add("${row.EVENT_TMSTP.stringValue()}");
How do I retrieve the locale-specific date format string in Flex / ActionScript 3? I am unable to find a method to return the actual format string (that which specifies the date format) based on the current locale. I am asking this question because I was hoping to find a way to convert a String to a Date based on the current SHORT date format for the locale. Java allows one to call:
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT, locale)
to retrieve an instance of DateFormat that formats according to the SHORT format based on the locale.
Does similar functionality exist in Adobe Flex (ActionScript 3) 3? If not, is there a reliable third party library that exists for this?
I'm just found this package that do the job. Here describe the class DateTimeFormatter:
var formatter:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.LONG, DateTimeStyle.SHORT);
var result:String = formatter.format(date);
Just cool.
Extending Gojan's answer:
private function cc(event:FlexEvent):void {
var formatter:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.SHORT, DateTimeStyle.NONE);
//now if publishDate is a mx:DateField, the formatString of spark and mx components are slightly different.
//So, we replace all d with D and y with Y
publishDate.formatString=replaceAll(formatter.getDateTimePattern(), ["d", "y"], ["D", "Y"]);
}
private function replaceAll(text:String, searchArray:Array, replArray:Array):String {
for (var i:int=0; i<searchArray.length; i++) {
var s:String=searchArray[i];
var d:String=replArray[i];
text=text.split(s).join(d);
}
return text;
}
Yeah I have to say Java is better with dates - you set the locale and automatically your dates are outputted correctly! I can't seem to find such a facility in Flex.
In order to output your dates correctly for each locale I think you have to do what is written in this article: http://livedocs.adobe.com/flex/3/html/help.html?content=l10n_1.html. Maybe you should do this, and in the same class just make these strings which you've pulled from the locale file available to the rest of your app, then you'll be able to operate on them.
Otherwise perhaps this guy's library will help you? I'm not sure.
http://flexoop.com/2008/12/flex-date-utils-date-and-time-format-part-ii/