3 回答

TA貢獻1852條經驗 獲得超1個贊
你能不能使用 LocalDateTime#atOffset 和 ZoneOffset#UTC?
LocalDateTime.parse(s, dateTimeFormatter).atOffset(ZoneOffset.UTC).toInstant().toEpochMilli()
正如@Andreas在注釋中指出的那樣,is-a ,因此您可以使用ZoneOffset
ZoneId
def dateTimeStringToEpoch(s: String, pattern: String): Long = LocalDateTime.parse(s, DateTimeFormatter.ofPattern(pattern)) .atZone(ZoneOffset.UTC) .toInstant() .toEpochMilli()

TA貢獻1804條經驗 獲得超7個贊
您可以更改此答案以返回 epoch millis,例如
static long dateTimeStringToEpoch(String s, String pattern) {
return DateTimeFormatter.ofPattern(pattern).withZone(ZoneOffset.UTC)
.parse(s, Instant::from).toEpochMilli();
}
或者,如果您甚至想避免臨時施工:Instant
static long dateTimeStringToEpoch(String s, String pattern) {
return DateTimeFormatter.ofPattern(pattern).withZone(ZoneOffset.UTC)
.parse(s, ta -> ta.getLong(ChronoField.INSTANT_SECONDS)*1000
+ta.get(ChronoField.MILLI_OF_SECOND));
}
請注意,兩者在這里都是可重用的組件,例如,您可以DateTimeFormatter.ofPattern(pattern).withZone(ZoneOffset.UTC)ta -> ta.getLong(ChronoField.INSTANT_SECONDS)*1000+ta.get(ChronoField.MILLI_OF_SECOND)
static final DateTimeFormatter MY_PATTERN
= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneOffset.UTC);
static final TemporalQuery<Long> EPOCH_MILLIS
= ta -> ta.getLong(ChronoField.INSTANT_SECONDS)*1000+ta.get(ChronoField.MILLI_OF_SECOND);
和
long millis = MY_PATTERN.parse("2018-07-21 18:30", EPOCH_MILLIS);
問題是,您希望在應用程序中出現多少個不同的格式字符串。通常,它不會像您必須解析的格式化日期那樣頻繁地更改。創建從格式字符串到預準備的緩存映射可能會有所幫助。無論如何,lambda 表達式是單例。DateTimeFormatter

TA貢獻1853條經驗 獲得超6個贊
在使用 UNIX Epoch 時,我建議使用它為紀元表示而設計的,并且默認會考慮,因為它是標準的一部分。java.time.InstantUTC
import java.time.Instant
object InstantFormat extends App {
//Instant.parse uses DateTimeFormatter.ISO_INSTANT
println(Instant.parse("2019-03-12T15:15:13.147Z"))
println(Instant.parse("2019-03-12T15:15:13Z"))
println(Instant.parse("2019-03-12T15:15:13Z").toEpochMilli)
println(Instant.parse("2019-03-12T15:15:13Z").getEpochSecond)
println(Instant.ofEpochMilli(1552403713147L))
println(Instant.ofEpochSecond(1552403713L))
}
輸出
2019-03-12T15:15:13.147Z
2019-03-12T15:15:13Z
1552403713000
1552403713
2019-03-12T15:15:13.147Z
2019-03-12T15:15:13Z
添加回答
舉報