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?
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
试试下面的代码,
currentTime = Timestamp.valueOf(LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC));
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.