我很難將一個字串的時間格式化為MM:DD::YY和唯一的時間。我從一個IP上得到了以下格式的時間
。2021-09-10T00:37: 42Z
我想用以下方式顯示日期和時間:
我想用以下方式顯示日期和時間。
09/08/2021。
時間
09:50PM
uj5u.com熱心網友回復:
將給定的字串決議為OffsetDateTime,然后從中獲取LocalDate和LocalTime部分。
import java.time.LocalDate。
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args){
String strDateTime = "2021-09-10T00:37:42Z" /span>;
OffsetDateTime odt = OffsetDateTime.parse(strDateTime)。
LocalTime time = odt.toLocalTime()。
LocalDate date = odt.toLocalDate()。
System.out.println(time)。
System.out.println(date)。
//#########Custom formats #########
DateTimeFormatter dtfDate = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH) 。
String formattedDateString = date.format(dtfDate)。
System.out.println(formattedDateString)。
DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("hh:mm a"/span>, Locale.ENGLISH);
String formattedTimeString = time.format(dtfTime)。
System.out.println(formattedTimeString)。
}
輸出:
00:37:42.
2021-09-10
09/10/2021
12:37 AM
。
從現代日期時間API*了解更多關于Trail: 日期時間.
根據Ole V.V.的重要評論進行更新:
OP--或他們的用戶--可能希望在他們自己的時區顯示日期和時間。
為了獲得特定時區的日期和時間部分,例如America/Los_Angeles,您應該將給定的日期時間字串決議為ZonedDateTime并使用ZonedDateTime#withZoneSameInstant將其轉換為特定時區的ZonedDateTime。其余的事情將保持與原來的答案相同。
演示:
import java.time.LocalDate。
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args){
String strDateTime = "2021-09-10T00:37:42Z" /span>;
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime)。
ZonedDateTime zdtLosAngeles = zdt.withZoneSameInstant(ZoneId.of("America/Los_Angeles"/span>)
LocalTime time = zdtLosAngeles.toLocalTime()。
LocalDate date = zdtLosAngeles.toLocalDate() 。
System.out.println(time)。
System.out.println(date)。
//#########Custom formats #########
DateTimeFormatter dtfDate = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH) 。
String formattedDateString = date.format(dtfDate)。
System.out.println(formattedDateString)。
DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("hh:mm a"/span>, Locale.ENGLISH);
String formattedTimeString = time.format(dtfTime)。
System.out.println(formattedTimeString)。
}
輸出:
17: 37: 42
2021-09-09
09/09/2021
05:37 PM
*由于任何原因,如果你必須堅持使用Java 6或Java 7,你可以使用ThreeTen-Backport,它將大部分的java.time功能回傳到Java 6 & 7。如果您正在為一個 Android 專案作業,而您的 Android API 水平仍然不符合 Java-8 的要求,請查看通過脫ugaring 提供的 Java 8 API和如何在 Android 專案中使用 ThreeTenABP。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/311912.html
標籤:
上一篇:Hive查詢-如何比較一個表中的日期,看它是否在另一個表中的開始和停止時間戳之間?
下一篇:安卓系統中的埃塞俄比亞日歷
