如何在不加载时区的情况下实现LocalDateTime与UTC的互转?
Nice question! I totally get wanting to skip the manual timezone loading steps while handling local-to-UTC (and vice versa) conversions with threetenbp on Android. Let's break down how to do this cleanly, while keeping things efficient.
First, a quick note: LocalDateTime is inherently timezone-agnostic, so converting between local time and UTC does require associating timezone info under the hood—but we can leverage built-in threetenbp constants to avoid manual "loading" (like parsing timezone strings) entirely.
Local Time to UTC
Your original code works, but we can simplify it using ZoneOffset.UTC—a pre-defined static constant in threetenbp that doesn't require any extra timezone parsing or loading. Here's the streamlined version:
// Get current local time, then convert to UTC LocalDateTime LocalDateTime localNow = LocalDateTime.now(ZoneId.systemDefault()); LocalDateTime utcNow = localNow.atOffset(ZoneOffset.UTC).toLocalDateTime();
Or even more concise:
LocalDateTime utcNow = LocalDateTime.now(ZoneId.systemDefault()) .atOffset(ZoneOffset.UTC) .toLocalDateTime();
UTC to Local Time
For the reverse conversion, we can use the same ZoneOffset.UTC constant to avoid manual UTC timezone creation:
// Start with a UTC LocalDateTime, convert to local time LocalDateTime utcTime = LocalDateTime.now(ZoneOffset.UTC); LocalDateTime localTime = utcTime.atOffset(ZoneOffset.UTC) .atZoneSameInstant(ZoneId.systemDefault()) .toLocalDateTime();
Why This Counts as "No Explicit Timezone Loading"
ZoneOffset.UTCis a built-in constant in threetenbp—no need to callZoneId.of("UTC")which involves string parsing and timezone data loading. It's lighter and faster.ZoneId.systemDefault()pulls the device's default timezone directly, which is a lightweight operation (threetenbp is already optimized for Android's system timezone handling).
Bonus: Using Instant for Even Cleaner Code
If your use case allows it, consider using Instant instead of LocalDateTime—Instant is inherently a UTC timestamp, so conversions become even simpler:
// Local time to UTC Instant Instant utcInstant = LocalDateTime.now(ZoneId.systemDefault()) .atZone(ZoneId.systemDefault()) .toInstant(); // UTC Instant to local time LocalDateTime localTime = LocalDateTime.ofInstant(utcInstant, ZoneId.systemDefault());
This avoids dealing with LocalDateTime's timezone-agnostic nature entirely, which can reduce confusion in time-sensitive code.
内容的提问来源于stack exchange,提问作者android developer

