这听起来可能非常有趣和基本,但我正在努力通过将纪元的秒数传递给它来在 Kotlin 中创建一个 DateTime 类型的对象。
我得到的示例要么是需要 API 级别 26 的库,要么只是谈论从 DD-MM-YYYY 字符串到其他字符串的格式转换。
到目前为止,我已经尝试过“LocalDateTime”、“Timestamp”、“Date”,但 Kotlin 要么拒绝识别它们,要么不同意函数参数,要么无法解决命名空间冲突。或者这些示例是 Java 的,它们在 Kotlin 中不起作用,或者在 Kotlin 中没有等价物。
使用 Date() 我收到错误“无法访问'':它在 Date() 中是私有(private)的”
使用 LocalDate、LocalDateTime,我收到 API 级别错误
使用时间戳我收到错误“不能使用提供的参数调用以下函数”。我将 Long 作为文档中提到的参数传递。但它期待“包裹”或“日期”。
有人可以帮忙吗?
最佳答案
更新:在最新版本的 Android 工具中,API 脱糖为旧版本的 Android 带来了许多内置于 Android 26 及更高版本中的 java.time 功能。
tl;博士
Date
, Calendar
, 或 SimpleDateFormat
. 避免遗留的日期时间类
遗留类,例如
Date
& Calendar
很糟糕,是由不了解日期时间处理的人创建的。这些类在几年前被 JSR 310 中定义的现代 java.time 类所取代。java.time
Instant
类替换 Date
类,都表示 UTC 中的时刻(零时分秒的偏移量)。Instant instant = Instant.now() ; // Capture the current moment in UTC.
Calendar
类,或更准确地说,它最常用的具体子类 GregorianCalendar
替换为 ZonedDateTime
.ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
兑换
最好完全避免遗留日期时间类。但有时您可能需要与尚未更新到 java.time 的旧代码进行互操作。在这种情况下,转换。看新
to…
/from…
添加到旧类的转换方法。Calendar calendar = GregorianCalendar.from( zdt ) ;
…和…ZonedDateTime zdt = ( ( GregorianCalendar ) calendar ).toZonedDateTime() ;
后端端口java.time 类内置于 Java 8 及更高版本以及 Android 26 及更高版本。
对于 Java 6 和 7,请使用 ThreeTen-Backport 中的反向端口。项目。大多数 java.time 功能都可以在其中找到。该项目由领导 java.time 项目和 JSR 310、Stephen Colebourne 的同一个人领导。 .
对于 26 之前的 Android,使用该反向端口对 Android 的适配,ThreeTenABP项目。
关于android - 在 Kotlin 中为小于或等于 16 的 API 级别创建 Date 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58456737/