1

We are using PO class to represent the sql DB and using Java JPA entity.In that class, we have one column as a field currentTime with Timestamp datatype and @version annotation from JPA.

@Version
private Timestamp currentTime;

whenever the entity gets updated, currentTime is updated with the latest time.

currentTime = new Timestamp(0); //this will create the new timestamp with current time.

but it’s currently taking the time from the server. I want to convert this time to UTC format before saving it to DB.

Anyone can help how can I convert the time to UTC time?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
sherin shaf
  • 143
  • 1
  • 1
  • 9

3 Answers3

1

I had a similar problem when I needed to parse the time from server but I needed to convert this time to UTC format before storing this information int MySQL DB. This was my solution:

     Instant dateConverted = LocalDateTime
                            .parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH))
                            .atZone(ZoneId.of("Europe/Bratislava")).toInstant();

     long epochTime = dateConverted.toEpochMilli() / 1000L;

Where dateTime is a String variable containing the date and time from server And I have used DateTimeFormatter to format my time to appropriate format. At the end I have added the zoneID of my timeZone and converted it to Instant

And at the end I have converted to seconds

Šimon
  • 338
  • 1
  • 4
  • 14
0

Try below code,

currentTime = Timestamp.valueOf(LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC));
Vivek
  • 376
  • 1
  • 14
  • Thanks. But Instant and LocalDateTime is not accessible from my project – sherin shaf Jan 17 '20 at 12:08
  • Please refer https://stackoverflow.com/questions/508019/how-to-store-date-time-and-timestamps-in-utc-time-zone-with-jpa-and-hibernate – Vivek Jan 17 '20 at 12:20
0
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
       sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String localTime = sdf.format(new Date(your_time_stamp));
    Date date = new Date();
    try {
        date = sdf.parse(localTime);//get local date
    } catch (ParseException e) {
        e.printStackTrace();
    }
Kukadiya Anil
  • 116
  • 2
  • 7
  • Thanks for your answer. But i need to convert the timestamp with @Version annotation to UTC timezone – sherin shaf Jan 17 '20 at 12:07
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jan 18 '20 at 21:32