Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert LocalDateTime to `"yyyy-MM-dd'T'HH:mm:ss'Z'"` format

I'm trying to parse the String in format "yyyy-MM-dd'T'HH:mm:ss'Z'" into LocalDateTime and if day is sunday or saturday i want to change date to monday and return in same format, i know i can add days by using plusDays

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

like image 962
Deadpool Avatar asked Oct 20 '25 04:10

Deadpool


2 Answers

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.
}

Table of date-time types in Java, both modern and legacy


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.

like image 109
Basil Bourque Avatar answered Oct 22 '25 18:10

Basil Bourque


    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().

like image 44
Ole V.V. Avatar answered Oct 22 '25 19:10

Ole V.V.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!