I have the following code that I want to migrate to Java 17:
Gradle dependency:
implementation 'org.jadira.usertype:usertype.core:7.0.0.CR1'
Entity:
import org.joda.time.DateTime;
@Entity
@Table(name = "logs")
public class Log {
@Column(name = "inserted_date")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime insertedDate;
}
.....
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yy-mm-dd'T'HH:mm:ss'Z'");
log.setInsertedDate(DateTime.now());
dateFormatter.print(log.getInsertedDate().withZone(DateTimeZone.UTC)));
I updated the code to this:
Entity:
import java.time.OffsetDateTime;
@Entity
@Table(name = "logs")
public class Log {
@Column(name = "inserted_date")
private OffsetDateTime insertedDate;
}
.....
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yy-mm-dd'T'HH:mm:ss'Z'");
log.setInsertedDate(OffsetDateTime.now());
dateFormatter.print(log.getInsertedDate().withZone(DateTimeZone.UTC)));
But I get error Cannot resolve method 'withZone' in 'OffsetDateTime'
. Do you know what is the proper way to update method withZone
?
edit: I tried this
from: log.setTimestamp(dateFormatter.print(auditLog.getInsertedDate().withZone(DateTimeZone.UTC)));
to: log.setTimestamp(dateFormatter.print(auditLog.getInsertedDate().atZoneSameInstant(ZoneOffset.UTC)));
I get for this line: auditLog.getInsertedDate().atZoneSameInstant(ZoneOffset.UTC)
error:
Cannot resolve method 'print(ZonedDateTime)'
Can you advice how to solve this?
First of all, it looks like your time format isn't what you intended it to be.
"yy-mm-dd'T'HH:mm:ss'Z'" would mean a format that prints:
year-minutes-days'T'Hours(24 hour format):minutes:secondsZ
example: 23-48-19T14:48:17Z
I'm assuming you want to follow years with month of the year and so the format should be:
"yy-MM-dd'T'HH:mm:ss'Z'"
example: 23-02-19T14:48:17Z
To know more about constructing patterns for formatting please refer the section "Patterns for Formatting and Parsing" in the java time api docs
Now, coming to your question,
You seem to be mixing the joda time library with java date time api. Written purely with the java date time api, your code should look something like:
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yy-MM-dd'T'HH:mm:ss'Z'");
log.setInsertedDate(OffsetDateTime.now());
log.setTimestamp(dateFormatter.format(auditLog.getInsertedDate().atZoneSameInstant(ZoneId.of("UTC"))));
PS: I know that working with date time objects can be frustrating and confusing in Java especially because there used to be more than one way to do it. I would recommend reading the java date time api tutorials to get a better understanding and to always use it (when writing in java 8+) to avoid confusion.