java.time.OffsetDateTime
Like the others I clearly recommend that you use java.time, the modern Java date and time API, for your date and time work.The class you need for a date and time with an offset such as -05:00 is OffsetDateTime
(not that surprising, is it?)
ZoneId zone = ZoneId.of("America/Monterrey");
OffsetDateTime currentDateAndTime = OffsetDateTime.now(zone);
System.out.println(currentDateAndTime);
Output when I ran the code just now:
2021-04-26T13:22:05.246327-05:00
If you want the offset for your own time zone, set zone
to ZoneId.systemDefault()
.
I am exploiting the facts that you were asking for ISO 8601 format and the classes of java.time produce ISO 8601 format from their toString
methods, so without any explicit formatter.
So if you need a String
, it’s just:
String currentDateAndTimeString = currentDateAndTime.toString();
System.out.println(currentDateAndTimeString);
Output is the same as before.
If you need a string with seconds and without fraction of second — you most probably don’t. As I wrote, the format that you asked for is ISO 8601, and according to the ISO 8601 standard the seconds and fraction of seconds are optional and understood to be zero when they are absent. So assuming that you need this string for an external service or other component requiring ISO 8601, the above string is fine. In any case: Edit: Truncate the fraction of second away and use the standard formatter:
String currentDateAndTimeWithSecondsOnly = currentDateAndTime
.truncatedTo(ChronoUnit.SECONDS)
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(currentDateAndTimeWithSecondsOnly);
Output when running just now:
2021-04-26T23:53:22-05:00
DateTimeFormatter.ISO_OFFSET_DATE_TIME
will output the seconds even if they are zero, and will leave out the fraction of second when it is zero (I needed to read the documentation very carefully to understand this).
Links