我在我的 Android 專案中使用了“單一日期和時間選擇器”庫,但它只以下面提到的格式回傳日期和時間。
“格林威治標準時間 12 月 28 日星期二 16:55:00 2021 年 05:30”
我想將其轉換為紀元時間格式。
圖書館:https : //github.com/florent37/SingleDateAndTimePicker
uj5u.com熱心網友回復:
替代解決方案 java.time.OffsetDateTime
這是一個替代解決方案,它利用java.time保留輸入的所有資訊String:
public static void main(String[] args) throws IOException {
// input
String dpDate = "Tue Dec 28 16:55:00 GMT 05:30 2021";
// define a formatter with the pattern and locale of the input
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
// parse the input to an OffsetDateTime using the formatter
OffsetDateTime odt = OffsetDateTime.parse(dpDate, dtf);
// receive the moment in time represented by the OffsetDateTime
Instant instant = odt.toInstant();
// extract its epoch millis
long epochMillis = instant.toEpochMilli();
// and the epoch seconds
long epochSeconds = instant.getEpochSecond();
// and print all the values
System.out.println(String.format("%s ---> %d (ms), %d (s)",
odt, epochMillis, epochSeconds));
}
輸出:
2021-12-28T16:55 05:30 ---> 1640690700000 (ms), 1640690700 (s)
LocalDateTime不應在此處使用A ,因為您可能會丟失有關偏移量的資訊,并且ZonedDateTime由于輸入缺少有關區域的資訊(例如"Asia/Kolkata"或 )"America/Chicago",因此無法使用 a ,它僅提供與 UTC 的偏移量。
如果你只是想得到紀元毫秒,你可以寫一個簡短的方法:
// define a constant formatter in the desired class
private static final DateTimeFormatter DTF_INPUT =
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
…
/**
* parses the input, converts to an instant and returns the millis
*/
public static long getEpochMillisFrom(String input) {
return OffsetDateTime.parse(input, DTF_INPUT)
.toInstant()
.toEpochMilli();
}
uj5u.com熱心網友回復:
您的日期格式是 EEE MMM dd HH:mm:ss zzzz yyyy
String date = "Tue Dec 28 16:55:00 GMT 05:30 2021";
try {
val sdf = SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy")
val mDate = sdf.parse(date)
val epochTime = TimeUnit.MILLISECONDS.toSeconds(mDate.time)
} catch (e: ParseException) {
e.printStackTrace()
}
變數epochTime將存盤秒數。
要將其轉換回您可以執行的格式 -
val sdf = SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy")
sdf.format(epochTime)
最新的 Java 8 需要最低 Api 級別 26
String date = "Tue Dec 28 16:55:00 GMT 05:30 2021";
DateTimeFormatter format = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
LocalDateTime parsedDate = LocalDateTime.parse(date, format);
val milliSeconds = parsedDate.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
uj5u.com熱心網友回復:
按照 Ansari 的回答,我這樣做是為了將其轉換為 Epoch
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.ENGLISH);
Date d1 = null;
try{
d1 = sdf3.parse("Tue Dec 28 16:55:00 GMT 05:30 2021");
epochTime = TimeUnit.MILLISECONDS.toSeconds(d1.getTime());
Log.e("epoch time", "onDateSelected: " epochTime );
}
catch (Exception e){ e.printStackTrace(); }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/388658.html
上一篇:將int值分配給影像以與更高價值的勝利進行比較(紙牌游戲)
下一篇:如何在發布aar中列印日志
