Java 日期区域格式为简单格式

Java dates zone format to simple format

是否可以将这种以字符串形式出现的 Java(可能是 ISO 8601)"2022-11-11T00:00:00" or this "2022-11-11T12:00:00+01:00" 格式转换为带有日期或时间的简单格式“yyyy-mm-dd”有点像 类,还是应该用字符串方法来完成?

示例:

you receive this -> "2022-11-11T00:00:00"
you convert to this -> "2022-11-11"

推荐方式:java.time

如果您需要根据值计算任何内容或者可能找出星期几,建议您使用 java.time:

public static void main(String[] args) {
    // example input in ISO format
    String first = "2022-11-11T00:00:00";
    String second = "2022-11-11T12:00:00+01:00";
    // parse them to suitable objects
    LocalDateTime ldt = LocalDateTime.parse(first);
    OffsetDateTime odt = OffsetDateTime.parse(second);
    // extract the date from the objects (that may have time of day and offset, too)
    LocalDate firstDate = ldt.toLocalDate();
    LocalDate secondDate = odt.toLocalDate();
    // format them as ISO local date, basically the same format as the input has
    String firstToBeForwarded = firstDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
    String secondToBeForwarded = secondDate.format(DateTimeFormatter.ISO_LOCAL_DATE); 
    // print the results (or forward them as desired)
    System.out.println(firstToBeForwarded);
    System.out.println(secondToBeForwarded);
}

这个例子的输出是

2022-11-11
2022-11-11

不推荐,但可能:String 操纵

如果你只需要

  • 提取日期部分(年、年月日)和
  • 您确定它将始终是您收到的 String 的前 10 个字符

您可以只取前 10 个字符:

String toBeForwarded = "2022-11-11T00:00:00".substring(0, 10);

此行将 "2022-11-11" 存储在 toBeForwarded 中。