Sea*_*ean 8 android kotlin localdatetime kotlinx-datetime
我正在将一些代码从使用 Java 8 转换LocalDatetime为使用该版本kotlinx-datetime,但我找不到任何格式化方法。具体来说,我正在替换FormatStyle.MEDIUM. 它们不存在并且我需要编写格式吗?
这是针对 Android 应用程序的。有没有我可以使用的 Android 特定库?或者我可以使用 Java 8 之前的方法来保持对旧版本 Android 的支持吗?
编辑(我的解决方案基于 Arvind 的答案):
fun Instant.toDateTimeString(formatStyle: FormatStyle = FormatStyle.MEDIUM): String {
val localDatetime = toLocalDateTime(TimeZone.currentSystemDefault())
val formatter = DateTimeFormatter.ofLocalizedDateTime(formatStyle)
return formatter.format(localDatetime.toJavaLocalDateTime())
}
Run Code Online (Sandbox Code Playgroud)
根据文档Instant,在 JVM 中,日期/时间类型(例如、LocalDateTime等)的实现TimeZone依赖于java.timeAPI。它还原生支持ThreeTen 向后移植项目,您可以使用该项目将大部分java.time功能向后移植到 Java 6 和 7。查看如何在 Android 项目中使用 ThreeTenABP以了解如何设置它。
如果您想替换 OOTB(开箱即用)格式,例如,您始终可以使用例如FormatStyle.MEDIUM定义自定义格式DateTimeFormatter
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.MEDIUM);
// Custom equivalent format with a fixed Locale
DateTimeFormatter dtfCustom = DateTimeFormatter.ofPattern("d MMM uuuu, HH:mm:ss", Locale.ROOT);
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.format(dtf));
System.out.println(ldt.format(dtfCustom));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
6 Nov 2021, 12:18:26
6 Nov 2021, 12:18:26
Run Code Online (Sandbox Code Playgroud)
从Trail: Date Time了解有关现代日期时间 API *的更多信息。
* 如果您正在从事 Android 项目,并且您的 Android API 级别仍然不符合 Java-8,请通过 desugaring 检查可用的 Java 8+ API。请注意,Android 8.0 Oreo 已提供对java.time. 检查此答案和此答案以了解如何将java.timeAPI 与 JDBC 结合使用。
| 归档时间: |
|
| 查看次数: |
8167 次 |
| 最近记录: |