0

I have DateAdapter for JPA date field:

public class DateAdapter extends XmlAdapter<String, Date> {
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss.SSS z");

    @Override
    public String marshal(Date v) throws Exception {
        synchronized (dateFormat) {
            return dateFormat.format(v);
        }
    }

    @Override
    public Date unmarshal(String v) throws Exception {
        synchronized (dateFormat) {
            return dateFormat.parse(v);
        }
    }
}

But if I try unmarshal String:

19990102T025555.000 GMT

unmarshal method returns

Sat Jan 02 05:55:55 MSK 1999

But I need return the same thing, which saved in base.

Roberto
  • 1,288
  • 5
  • 23
  • 47
  • 2
    A `Date` value doesn't know about a time zone. If you need to be able to store different time zones, you'll need to use a different type. – Jon Skeet Dec 14 '18 at 09:27
  • 1
    You should not use `Date` class which is deprecated for a while – veben Dec 14 '18 at 09:37
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). While `Date` is not officially deprecated, it is certainly long outdated, so you should treat it as though it were. – Ole V.V. Dec 14 '18 at 09:47
  • The code you already have *does* save the correct date and time to the database. However, a modern JPA implementation will accept one of `OffsetDateTime` and `Instant` for persisting and will also give you the same type back, so there’s no need for you to use the poorly designed and long outdated `java.util.Date` class at all. – Ole V.V. Dec 14 '18 at 09:50
  • Possible duplicate of [want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format](https://stackoverflow.com/questions/8745297/want-current-date-and-time-in-dd-mm-yyyy-hhmmss-ss-format) – Ole V.V. Dec 14 '18 at 09:52
  • As an aside, your format is a peculiar mix of [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) and something that isn’t ISO 8601, and I am in severe doubt whether it’s got any good use. Internally in your program you should use date-time objects, not strings. For presentation to the user, I think that they will be happier with a localized format like for example `14 дек. 2018 г., 13:09:45 Москва, стандартное время`. – Ole V.V. Dec 14 '18 at 10:10

1 Answers1

0

If you are able and willing to replace Date with ZonedDateTime (from Java 8), you can do this:

private final DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss.SSS z");

ZonedDateTime date = ZonedDateTime.parse("19990102T025555.000 GMT", dateFormat);
System.out.println(date);                    // 1999-01-02T02:55:55Z[GMT]
System.out.println(dateFormat.format(date)); // 19990102T025555.000 GMT
Mark Jeronimus
  • 9,278
  • 3
  • 37
  • 50