Considering the pattern you provided, an OffsetDateTime
would be my choice:
public static void main(String[] args) {
OffsetDateTime nowWithOffset = OffsetDateTime.now();
System.out.println(nowWithOffset);
}
This output (some seconds ago)
2020-09-18T10:55:02.832+02:00
As you can see, your desired pattern matches the default one used by an OffsetDateTime
.
I would make the attribute date
an OffsetDateTime
instead of a String
and provide a simple method for a String
representation, maybe like this:
public String getDateAsString() {
return date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX");
}
and if you receive such a String
and want to set your attribute, use a parameterized constructor or a setter / setting method, e.g.
public void setDateFromString(String date) {
this.date = OffsetDateTime.parse(
date,
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX"));
}
and better replace the y
in the pattern by a u
, because a y
could cause trouble in some situations where an era would be required.