Avatar ·

如何在 Android 的 Kotlin 中获取当前 timestamp(时间戳)?

大家好!我是一名 Kotlin 的 Android 开发新手,遇到了一个简单但重要的问题。我需要在应用中获取当前 timestamp(时间戳),例如将其写入数据库或发送到服务器。我知道在 Java 中使用 System.currentTimeMillis(),但在 Kotlin 中我看到很多不同的方法,感到困惑。

以下是我尝试过的:

val timestamp1 = System.currentTimeMillis()
val timestamp2 = Date().time
val timestamp3 = Calendar.getInstance().timeInMillis

所有这些方法都返回一些长数字。但我不确定在 Android 中哪个是正确的?它们之间有区别吗?还有,能否以秒而不是毫秒为单位获取 timestamp?我听说过 Java 8 的 Instant.now(),但在 Android 中并非所有地方都支持。

请告诉我,在 2024 年针对 Kotlin 和 Android 的最佳实践是什么?是否需要添加某些依赖?