Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OffsetDateTime toString() return different format date string

Tags:

java

date

I have date in this format yyyy-MM-dd'T'HH:mm:ss'Z', but while i'm parsing this using OffsetDateTime.parse(date); it returns the string by elimination seconds

Logic : Get the day from date, if it is Saturday or Sunday change day to monday and return the date String

String date = "2018-12-30T06:00:00Z";

System.out.println(date);

try {
    OffsetDateTime dateTime = OffsetDateTime.parse(date);

    System.out.println(dateTime);           //2018-12-30T06:00Z

    DayOfWeek day = dateTime.getDayOfWeek();
    // check if price change  date is Sunday or Saturday and change it to Monday
    if (day.equals(DayOfWeek.SATURDAY) || day.equals(DayOfWeek.SUNDAY)) {

        String finalDateTime = dateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).toString();
         System.out.println(finalDateTime);      //2018-12-31T06:00Z
    }else {
        System.out.println(date);
    }
    }catch(Exception ex) {
        System.out.println(ex);
        System.out.println(date);
    }   

I need to return string as same input format yyyy-MM-dd'T'HH:mm:ss'Z'

like image 465
Deadpool Avatar asked Dec 13 '22 13:12

Deadpool


1 Answers

As per OffsetDateTime.toString() method javadoc the shortest possible format for the value is used while omitted parts are implied to be zero. The shortest possible format for 2018-12-30T06:00:00Z is uuuu-MM-dd'T'HH:mmXXXXX so the seconds and nanos are skipped:

The output will be one of the following ISO-8601 formats:

  • uuuu-MM-dd'T'HH:mmXXXXX
  • uuuu-MM-dd'T'HH:mm:ssXXXXX
  • uuuu-MM-dd'T'HH:mm:ss.SSSXXXXX
  • uuuu-MM-dd'T'HH:mm:ss.SSSSSSXXXXX
  • uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSSXXXXX

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

If you need a precise format use a DateTimeFormatter instance with specific pattern to output the date:

String date = "2018-12-30T06:00:00Z";
OffsetDateTime dt = OffsetDateTime.parse(date);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
System.out.println(fmt.format(dt));
like image 183
Karol Dowbecki Avatar answered Mar 01 '23 23:03

Karol Dowbecki