是否可以將這種 "2022-11-11T00:00:00" or this "2022-11-11T12:00:00 01:00"
以字串形式出現的 Java(可能是 ISO 8601)格式轉換為具有日期或時間類的簡單格式“yyyy-mm-dd”,或者應該使用字串方法來完成?
例子:
you receive this -> "2022-11-11T00:00:00"
you convert to this -> "2022-11-11"
uj5u.com熱心網友回復:
推薦方式: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
您收到的 s的前 10 個字符
你可以簡單地取前 10 個字符:
String toBeForwarded = "2022-11-11T00:00:00".substring(0, 10);
該行將存盤"2022-11-11"
在toBeForwarded
.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470814.html