Spring Hibernate JPA Java8 OffsetTime - spring

I have created an Hibernate Entity which has a OffsetTime column. While saving a time value with time offset e.g (+05:00), it discards time offset, and saves the time with the time offset according to the system timezone. Here is my column in entity:
#Column(name = "start_time", nullable = false)
private OffsetTime startTime;
Then if I try to save "12:15+01:00". It save "12:15+00:00", if my machine is in UTC timezone, if my machine is in IST timezone, it save "12:15+05:00". I want it to save "12:15+01:00" irrespective of machine's timezone.
Please suggest what I need to correct/review to ensure I fix this issue.
Thanks.

Question is how do you do the setting of the value. You didn't show your setter method. You either parse it from String or operate some instance of Temporal that you convert to OffsetTime in either case you will need to provide the desired offset if you don't want to use the default one. Say that you want to save current time with given offset. So you will have to do this:
OffsetTime startTime = OffsetTime.of(LocalTime.now, ZoneOffset.of("+05:00");
See method of() as well of other methods of OffsetTime

Related

Spring Boot Query on Date field without time

I have an entity with a Date field with type of java.util.Date, and this field in oracle db has the timestamp type.
the problem is that when i use the repository to find by given specs, it returns nothing for the given date.
It only happens when i want the exact equal date. it works fine with greaterThen and lessThen and that's because the time of the saved records are different.
how could I ignore the time of records and fetch them only for the given date?
Thanks a million
I think you need to look at #Temporal #JsonFormat annotations. Link
Sample usage;
#Temporal(TemporalType.TIMESTAMP)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MMdd'T'HH:mm:ss")
protected Date lastUpdate;
because the data was saved with the time best way was to do it with between condition from 00:00 to 23:59 in that day. special thanks to this link :
Spring Data Querying DateTime with only Date
but i solved the problem by creating a view from that table and removing the time from the date in oracle.

Convert TimeStamp To Joda DateTime Without Any Timezone Conversion

I have timestamp value in Oracle database column stored in UTC. I want to read it through spring's jdbcTemplate and convert it to joda DateTime object without any timezone conversion i.e. read it as is without converting or losing timezone.
For e.g. if the input timestamp is 2019-03-08 15:07:37.232, I would like to have the DateTime object with the value 2019-03-08T15:07:37.232Z
How can I achieve this?
Note this code - new DateTime(timestamp.getTime(), DateTimeZone.UTC)) does not help since it assumes that the input timestamp is in local timezone and reconverts it to UTC. For the above input is 2019-03-08 15:07:37.232 the outcome comes to 2019-03-08T09:37:37.232Z
Thanks.
One solution that worked was to change the way the timestamp column value is retrieved from the database. The below snippet works for converting a timestamp column value to joda DateTime without losing/converting the timezone
new DateTime(resultSet.getTimestamp("CreatedDateTime",
Calendar.getInstance(TimeZone.getTimeZone("UTC"))), DateTimeZone.UTC)
Hope that helps others too.
If you already have a DateTime object there is method
public DateTime withZone(DateTimeZone newZone)
which would return a copy of datetime with a different time zone, preserving the millisecond instant
eg:- dateTime.withZone(DateTimeZone.UTC)

Date timezone getting changed when using spring boot default jackson mapping

I have spring boot rest service which call another service xyz and receive date in format yyyy-MM-ddXXX from json. But time Zone of of date is getting changed in my service response. Suppose I am getting date in JSON from service xyz as "date": "2018-08-27-07:00" but my service response is returning date : "2018-08-27-04:00". Offset getting changed. Date field in my POJO is . I want to use the same offset I am getting from backend service and it can be any offset.
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-ddXXX")
private Calendar date;
The problem is that Calendar (and Date) use implicit time conversions to adjust it to your time zone. And almost always it is something that not expected.
To avoid this use java.time classes (such as OffsetDateTime or ZonedDateTime, or even LocalDateTime if you do not need to work wit time zones).
And small offtopic advice: try to use time format aligned to ISO8601 standard (like 2018-08-24T22:30:00)

Spring Boot - Jackson - datetime timezone problems

I am having trouble dealing with timezones across my projects.
First of all, I have two use cases:
1) A user input a DateTime with datepicker in HTML and we want to save it without timezone in the database. example input: 10.04.2018 18:00 --> we want to save exactly this date and also want to retrieve exactly this date, no matter what the timezone is on the client side. (we can think about this like a never changing date string)
2) The more common, second use case is, we enter a DateTime with datepicker in HTML and want to save the date with timezone in the database. For example:
The Clients Timezone is Europe/Istanbul and he inputs a DateTime: 10.04.2018 18:00. Now we want to save this date as Europe/Berlin in Database which would be 10.04.2017 17:00. When we retrieve the date we want to convert the date to the timezone of the client. In this example, if a client with timezone Europe/Berlin wants to retrieve the database date 10.04.2017 17:00 we would exactly retrieve: 10.04.2017 17:00. But if a client with timezone Europe/Istanbul wants to retrieve the same value 10.04.2017 17:00 we would retrieve: 10.04.2018 18:00
Now I tried to achieve this behavior by settings the webapp timezone to Europe/Berlin and parse the dates for each use case with the Moment.js library on client site. Therefore, I always expect to retrieve a Date in the timezone Europe/Berlin from my web service and then either convert to the local time zone or let the date as it is.
I am using Spring Boot with following version:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
In my application.properties file i set those values:
spring.jpa.properties.hibernate.jdbc.time_zone=Europe/Berlin
spring.jackson.deserialization.adjust-dates-to-context-time-zone=false
spring.jackson.time-zone=Europe/Berlin
MyApplication:
#PostConstruct
void started() {
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"));
}
My attributes in my model class look like this:
#Column(name = "timeFrom")
#Temporal(TemporalType.TIMESTAMP)
private Date timeFrom;
#Column(name = "timeTo")
#Temporal(TemporalType.TIMESTAMP)
private Date timeTo;
For the first use case, where I want a date which is not parsed to the local time zone i use this code to retrieve my date in javascript: (because I know that my date in database is Europe/Berlin, I convert it to this time zone in order to retrieve the exact same date as it is in the database)
var countHours = moment(timeTracking["countHours"]).tz('Europe/Berlin').format('HH:mm');
For the second use case, where i want to convert my Europe/Berlin date from the database to the local client time zone i use this code:
var timeFrom = moment(timeTracking["timeFrom"]).format('YYYY-MM-DD HH:mm');
When i pass a date from javascript via JSON and ajax to my backend i use this:
moment($("#timeRecord-timeFrom").val()).valueOf()
On serverside i receive a timestamp in milliseconds and i parse it like that:
Date dateFrom = new Date(node.get("startTime").asLong());
Now the weird part: everything I posted above is working perfectly fine on my localhost (local machine). However, as soon as I push my war file to the live system (Jelastic Spring Boot Server) I have an offset of 2 hours in my date.
The strangest part is when I commit my date via ajax and retrieve the persisted object afterward everything is fine and I have no offset. But when I do a full page reload, I immediately receive the date with 2 hours offset. However, the date is still correct in the database.
As this is only happening on the live system and not on the localhost I have no clue how to fix this.
What am I doing wrong? Would it be better to switch to JodaTime or Java8 LocalDateTime? I already tried it but ran into several build errors so stick with java.util.Date.
A best practice tutorial for my use cases would be also appreciated.

Jodas LocalDateTime with Spring Data and Couchbase has no timezone

I wanna persistant an object with LocalDateTime fields with spring data and a couchbase behind in a spring boot app.
Here are the fieldmapping:
#Field
private LocalDateTime start;
#Field
private LocalDateTime end;
When I save the object then the dates are stored as numbers in couchbase.
Here are the stored data in couchbase:
"start": 1518818215508,
So the problem is, if I store an LocalDateTime e.g at 10.00, and then read it from db the result is 09:00 instead of 10:00 because of my local time +1:00.
In Postgres I would save the date in an column with mapping: columnDefinition= "TIMESTAMP WITH TIME ZONE"
How I can solve this problem in couchbase?
JSON (famously) has no date format (unlike relational databases which have a sprawling number of different formats). If you want to store timezone data in JSON, here are two options I can think of:
Using a string instead of a number, and then using something like ISO-8601.
Store the epoch time as you currently are as a UTC value, but also store a separate number field that represents a timezone offset from UTC
I would recommend going with the first approach.
I'm no Spring/Java expert, but a quick look at the documentation says you can do this by setting system property org.springframework.data.couchbase.useISOStringConverterForDate to true

Resources