How to convert LocalDateTime to `"yyyy-MM-dd'T'HH:mm:ss'Z'"` format
Solution 1
String str = "2018-09-22T12:30:10Z";
OffsetDateTime dateTime = OffsetDateTime.parse(str);
DayOfWeek dow = dateTime.getDayOfWeek();
if (dow.equals(DayOfWeek.SATURDAY) || dow.equals(DayOfWeek.SUNDAY)) {
dateTime = dateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
}
System.out.println(dateTime);
Output from this snippet was:
2018-09-24T12:30:10Z
It takes the date from the string, in this case September 22, and since it was a Saturday, it does make the adjustment to the following Monday. It doesn’t use your JVM’s time zone setting.
Your string is in ISO 8601 format, the standard format that the classes from java.time parse and produce as their default, so there is no need for specifying the format through any DateTimeFormatter
. The Z
in the string denotes UTC (in other words, offset 0 from UTC), so parse it as an offset and into an OffsetDateTime
rather than a LocalDateTime
to keep all information from the string. This also makes it easy to return the same format.
If you need to return a String
, use dateTime.toString()
.
Solution 2
tl;dr
Use Instant
, not LocalDateTime
.
Instant // Represent a moment as seen in UTC (an offset of zero hours-minutes-seconds).
.parse( "2018-01-23T01:23:45.123456789Z" ) // Parse text in standard ISO 8601 format where the `Z` on the end means UTC.
.truncatedTo( java.time.temporal.ChronoUnit.SECONDS ) // Lop off any fractional second.
.plus( // Date-time math.
Duration.ofDays( 2 ) // Represent a span-of-time not attached to the timeline.
) // Returns another `Instant` object rather than altering the original.
.toString() // Generate text in standard ISO 8601 format.
2018-01-25T01:23:45Z
ISO 8601
parse the String in format "yyyy-MM-dd'T'HH:mm:ss'Z'" into LocalDateTime
You cannot. Or should not use LocalDateTime
for this purpose.
Your input string is in standard ISO 8601 format. The Z
on the end means UTC, and is pronounced “Zulu”. You should never ignore this character, as you seem to be intending by the use of single-quote marks around it.
Instant
Parse such a string as a Instant
, a moment in UTC.
Instant instant = Instant.parse( "2018-01-23T01:23:45.123456789Z" ) ;
LocalDateTime
The LocalDateTime
class cannot represent a moment. It purposely lacks any concept of time zone or offset-from-UTC. This class represents potential moments along a range of about 26-27 hours, the various time zones currently in use around the globe.
OffsetDateTime
To communicate with a database via JDBC, use OffsetDateTime
.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
ZonedDateTime
To see the moment of that Instant
through the lens of the wall-clock time used by the people of a certain region (a time zone), apply a ZoneId
to get a ZonedDateTime
object.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Weekend
To test for the weekend, use the DayOfWeek
enum in an EnumSet
.
Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SATURDAY ) ;
For any given moment, the date varies around the globe by time zone. For example, a few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec. So adjust your Instant
into the time zone appropriate to your business problem, as shown above.
Compare by extracting a DayOfWeek
enum object from your ZonedDateTime
.
DayOfWeek dow = zdt.getDayOfWeek() ;
Compare to see if it is a weekend or weekday.
ZonedDateTime target = zdt ; // Initialize.
if( weekend.contains( dow ) ) {
target = zdt.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) ; // Move from one day to another.
}
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
-
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
-
Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
-
Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Solution 3
Try this one
String str = "2018-09-22T12:30:10Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
System.out.println(dateTime.plusDays(2).format(formatter));
output:
2018-09-24T12:30:10Z
Solution 4
Convert to Instant
time.
System.out.println(dateTime.plusDays(2).toInstant(ZoneOffset.UTC)));
Deadpool
Updated on June 16, 2022Comments
-
Deadpool almost 2 years
I'm trying to parse the String in format
"yyyy-MM-dd'T'HH:mm:ss'Z'"
intoLocalDateTime
and if day issunday
orsaturday
i want to change date tomonday
and return in same format, i know i can add days by usingplusDays
String str = "2018-09-22T12:30:10Z"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); LocalDateTime dateTime = LocalDateTime.parse(str, formatter); System.out.println(dateTime.plusDays(2)); //2018-09-24T12:30:10
But i want to return in format
2018-09-24T12:30:10Z
-
Mike 'Pomax' Kamermans over 5 yearsYour question seems to contradict itself. You first say you want to return the date in the same format you read it in, then you end by saying you want to return the date in a completely different format. You also say you want to replace the day, but your code doesn't show you doing this, so are you asking two questions in one? Or is there only one question and the other "want" is not important?
-
Ole V.V. over 5 yearsYour input string is in UTC. Do you want to check for Saturday or Sunday in your own time zone or in UTC? It’s never the same day in all time zones.
-
Deadpool over 5 yearsyes i want to check in UTC? all my systems are in UTC timezone probably it will take default from system right ?
-
Pshemo over 5 yearsSorry but is your question (1) how to print result of
dateTime.plusDays(2)
in form2018-09-24T12:30:10Z
, or (2) how to check if day of week ofdateTime
is Saturday or Sunday? -
Deadpool over 5 yearsi want to return in this format
2018-09-24T12:30:10Z
, but i got bunch of answers
-
-
Andreas over 5 yearsMissing test for "if day is sunday or saturday"
-
Andreas over 5 yearsMissing test for "if day is sunday or saturday"
-
Hadi J over 5 yearsit is logic for OP!! not me. and just display how display it in expected format that OP wants to have
-
drowny over 5 yearsI added for how to write same format. Sunday and monday not a problem and totaly i think.
-
Ole V.V. over 5 yearsIn all fairness, the asker didn’t seem to ask for this logic, @Andreas. “i know i can add days by using
plusDays
”, not perfect, but not central to the question as I understood it (I was just trying to be kind and provided my version of that logic anyway). -
drowny over 5 yearsYour answer is showing all result. My solution is about how to show same format date.