saga56 saga56 - 2 months ago 6x
Java Question

Java Date problems with TIMEZONE

I am struggling on this for days.

I have a date field, that gives a date on 'yyyy-MM-dd' format.

My Object have this field like this

private Date finishdate;

I am on UTC, and this need to work all over the world, so on UTC-7 or UTC+7

On DataBase this value need to be store with 0 hours.

When the finishdate is filled, the format give me the timezone, so, for example:

I want 2014-10-01, with ZERO HOURS AND MINUTES AND SECONDS, on diferent timezones I catch:

2014-10-01 07:00:00:000
2014-09-01 17:00:00:000

The problem seams to be because of the Date liybrary, and i've found a solution with JODA Library, but i was told not to used it, and I need to find another solution.

So, need to convert to UTC Date, all dates,or other thing, but the day must be the same, like 1 October.

Anyone pass through this?


Solution to this issue.

We made an Custom Deserializer to every object of the type Date.

On ObjectMapperFactory, where we serialize or deserialize, i mapped to another class like this:

 module.addDeserializer(Date.class, new DateDeserializerByDefault());

Then, on this class we did:

private static SimpleDateFormat dateFormatWithoutTimezome = new SimpleDateFormat("yyyy-MM-dd");
private static SimpleDateFormat dateFormatWithTimezone= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
private static Pattern pattern = Pattern.compile("([0-9]{4})-([0-9]{2})-([0-9]{2})");

public Date deserialize(JsonParser jparser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String content = jparser.getValueAsString();
    DateFormat format=(pattern.matcher(content).matches()) ? dateFormatWithoutTimezome : dateFormatWithTimezone;        

try {
    return format.parse(content);
} catch (ParseException e) {
    throw new JsonParseException("Date parse failed", jparser.getCurrentLocation(),e);

And with this, when we receive Dates on diferent format, or with timezone to be stor we can change it to what we want.

I Hope this solution can help, I was stuck on this for 3,5 days. Dates are a pain in the a**.