OffsetDateTime toString()返回不同格式的日期字符串

时间:2019-01-02 16:55:17

标签: java java-date

我的日期格式为<div cdkDropList [cdkDropListData]="capitals" #capitalsList="cdkDropList" [cdkDropListConnectedTo]="countryList"> <div cdkDrag (cdkDragReleased)="onDragReleased($event)" cdkDragBoundary=".row" class="bg-info text-center border p-2" *ngFor="let capital of capitals">{{ capital }} </div> </div> <div cdkDropList cdkDropListDisabled [cdkDropListData]="countries" #countryList="cdkDropList" [cdkDropListConnectedTo]="capitalsList" (cdkDropListDropped)="onDropListDropped($event)"> <div cdkDrag cdkDragDisabled class="text-center border p-2" *ngFor="let country of countries">{{ country }} </div> </div> ,但是当我使用yyyy-MM-dd'T'HH:mm:ss'Z'解析日期时,它通过消除OffsetDateTime.parse(date);返回字符串。

逻辑::从日期获取日期,如果是secondsSaturday,则将日期更改为星期一并返回日期字符串

Sunday

我需要以相同的输入格式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); } 返回字符串

1 个答案:

答案 0 :(得分:3)

按照OffsetDateTime.toString()方法javadoc,使用该值的最短格式,而省略的部分隐含为零。 2018-12-30T06:00:00Z的最短格式为uuuu-MM-dd'T'HH:mmXXXXX,因此跳过了秒和纳秒:

  

输出将是以下ISO-8601格式之一:

     
      
  • 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
  •   
     

使用的格式将是最短的格式,用于输出被省略部分隐含为零的时间的完整值。

如果您需要精确的格式,请使用具有特定模式的DateTimeFormatter实例输出日期:

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));