【发布时间】:2022-01-22 16:05:57
【问题描述】:
我在我的 Android 项目中使用“单一日期和时间选择器”库,但它只返回下面提到的格式的日期和时间。
“格林威治标准时间 12 月 28 日星期二 16:55:00+2021 年 05:30”
我想把它转换成纪元时间格式。
【问题讨论】:
标签: java android xml datepicker epoch
我在我的 Android 项目中使用“单一日期和时间选择器”库,但它只返回下面提到的格式的日期和时间。
“格林威治标准时间 12 月 28 日星期二 16:55:00+2021 年 05:30”
我想把它转换成纪元时间格式。
【问题讨论】:
标签: java android xml datepicker epoch
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,因为您可能会丢失有关偏移量的信息,并且由于输入缺少有关"Asia/Kolkata"或"America/Chicago"之类的区域的信息,因此无法使用ZonedDateTime,它只是提供与 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();
}
【讨论】:
你的日期格式是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();
【讨论】:
按照安萨里的回答,我这样做是为了将其转换为纪元
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(); }
【讨论】: