2

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

Saikrishna Rajaraman
  • 3,205
  • 2
  • 16
  • 29
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • Your 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? – Mike 'Pomax' Kamermans Sep 26 '18 at 17:32
  • 2
    Your 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. – Ole V.V. Sep 26 '18 at 17:32
  • yes i want to check in UTC? all my systems are in UTC timezone probably it will take default from system right ? – Ryuzaki L Sep 26 '18 at 17:34
  • 1
    Sorry but is your question (1) how to print result of `dateTime.plusDays(2)` in form `2018-09-24T12:30:10Z`, or (2) how to check if day of week of `dateTime` is Saturday or Sunday? – Pshemo Sep 26 '18 at 18:12
  • i want to return in this format `2018-09-24T12:30:10Z`, but i got bunch of answers – Ryuzaki L Sep 26 '18 at 18:35

4 Answers4

9

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?

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
4
    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().

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
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

Hadi J
  • 16,989
  • 4
  • 36
  • 62
1

Convert to Instant time.

System.out.println(dateTime.plusDays(2).toInstant(ZoneOffset.UTC)));
drowny
  • 2,067
  • 11
  • 19
  • Missing test for *"if day is sunday or saturday"* – Andreas Sep 26 '18 at 17:45
  • 1
    I added for how to write same format. Sunday and monday not a problem and totaly i think. – drowny Sep 26 '18 at 17:48
  • 1
    In 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). – Ole V.V. Sep 26 '18 at 17:48
  • Your answer is showing all result. My solution is about how to show same format date. – drowny Sep 26 '18 at 17:51