我必須將在美國出生的人的出生日期轉換為 Epoch 并將其存盤在資料庫中。現在,我從遺留系統中獲取兩種不同格式的出生日期:yyyy-MM-dd HH:mm:ss & dd-MMM-yyyy。
如何在考慮區域偏移的情況下正確轉換它?我當前的代碼看起來像這樣,但由于區域偏移而出現問題。解決這個問題的正確方法是什么?
public class DateTimeUtils
{
public static Instant parseBirthDateTime(String birthdate)
{
if (birthdate != null)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date date;
try
{
date = formatter.parse(birthdate);
}
catch (Exception e)
{
if (!e.getMessage().contains("Unparseable date"))
{
if (Logger.isErrorEnabled())
Logger.error(e);
}
formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
try
{
date = formatter.parse(birthdate);
}
catch (Exception ex)
{
if (Logger.isErrorEnabled())
Logger.error(e);
return Instant.parse("0001-01-01T00:00:00.00Z");
}
}
if (date != null)
{
return Instant.ofEpochMilli(date.getTime());
}
else
{
return Instant.parse("0001-01-01T00:00:00.00Z");
}
}
return Instant.parse("0001-01-01T00:00:00.00Z");
}
}
uj5u.com熱心網友回復:
2014 年 3 月,java.timeAPI 取代了容易出錯的遺留日期時間 API。從那時起,強烈建議使用這個現代日期時間 API。
Instant您需要為每個要將它們轉換為從中獲取 Epoch 值的日期時間值設定時區。
使用DateTimeFormatterBuilder,您可以創建一個DateTimeFormatter具有默認時間值的 as 00:00,然后使用相同的格式化程式將日期和日期時間決議為LocalDateTime.
演示:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("[dd-MMM-uuuu[ HH:mm]][uuuu-MM-dd HH:mm:ss]")
.parseCaseInsensitive()
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.toFormatter(Locale.ENGLISH);
String arr[] = {"2022-11-14 08:40:50", "14-Nov-2022"};
for (String sdt : arr) {
LocalDateTime ldt = LocalDateTime.parse(sdt, formatter);
// Assuming you have the time-zone for each value. For the demo, I
// have used here only one time-zone.
ZoneId zodeId = ZoneId.of("America/New_York");
long epoch = ldt.atZone(zodeId).toInstant().toEpochMilli();
System.out.println(epoch);
}
}
}
輸出:
1668433250000
1668402000000
從Trail:Date Time了解有關現代日期時間 API 的更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/533673.html
上一篇:是的日期驗證
下一篇:計算達到給定截止日期的案例數
