如何将LocalDateTime转换为“" yyyy-MM-dd'T'HH:mm:ss'Z'"格式 [英] How to convert LocalDateTime to `"yyyy-MM-dd'T'HH:mm:ss'Z'"` format

查看:2304
本文介绍了如何将LocalDateTime转换为“" yyyy-MM-dd'T'HH:mm:ss'Z'"格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将格式为"yyyy-MM-dd'T'HH:mm:ss'Z'"的字符串解析为LocalDateTime,如果day是sundaysaturday,我想将日期更改为monday并以相同的格式返回,我知道我可以使用plusDays

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

但是我想以2018-09-24T12:30:10Z

推荐答案

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

此代码段的输出为:

2018-09-24T12:30:10Z

2018-09-24T12:30:10Z

它从字符串中获取日期,在这种情况下为9月22日,并且由于它是星期六,所以它确实将调整为下一个星期一.它不使用您的JVM的时区设置.

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.

您的字符串采用ISO 8601格式,这是java.time中的类解析并作为其默认值生成的标准格式,因此无需通过任何DateTimeFormatter指定格式.字符串中的Z表示UTC(换句话说,与UTC的偏移量为0),因此将其解析为一个偏移量,并转换为OffsetDateTime而不是LocalDateTime,以保留字符串中的所有信息.这也使返回相同格式的操作变得容易.

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.

如果需要返回String,请使用dateTime.toString().

If you need to return a String, use dateTime.toString().

这篇关于如何将LocalDateTime转换为“" yyyy-MM-dd'T'HH:mm:ss'Z'"格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆