android - Kotlin - 将 UTC 时间转换为本地时间

标签 android android-studio kotlin

我正在尝试将 UTC 字符串日期转换为本地时间,以便采用更易读的格式。 我的 Activity 布局中有一个 textView:

<TextView
    android:id="@+id/dateTv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/titleTv"
    tools:text="Published Date" />

在我的 Activity 中:

class FullArticleActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_full_article)

    val articleJson = intent.getStringExtra(ARTICLE_KEY)


    if(!articleJson.isNullOrBlank()) {
      val article = Gson().fromJson<Article>(articleJson, Article::class.java)

        val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ", Locale.getDefault())
        formatter.timeZone = TimeZone.getTimeZone("UTC")
        val formattedDate = formatter.parse(article.publishedAt)

      titleTv.text = article.title
      //UTC string
      dateTv.text = article.publishedAt
      contentTv.text = article.content

publishedAt 字符串采用这种格式,来自 API 调用 "2018-12-10T19:48:39Z"。如何将此 ZULU 时间格式转换为本地时间?

最佳答案

尝试使用扩展函数

fun String.toDate(dateFormat: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone = TimeZone.getTimeZone("UTC")): Date {
val parser = SimpleDateFormat(dateFormat, Locale.getDefault())
parser.timeZone = timeZone
return parser.parse(this)
}

fun Date.formatTo(dateFormat: String, timeZone: TimeZone = TimeZone.getDefault()): String {
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
formatter.timeZone = timeZone
return formatter.format(this)
}

用法:

"2018-09-10 22:01:00".toDate().formatTo("dd MMM yyyy")

输出:“2018 年 9 月 11 日”

关于android - Kotlin - 将 UTC 时间转换为本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713934/

相关文章:

android - 卫星导航语音开始/停止时通知应用程序

Android studio 需要为 Mac Monterey 更新

java - Android Studio 3.1 无法解析符号主题

安卓工作室 3.1.3 错误 : Unable to resolve dependency

android - Kotlin !!运算符使用使代码不清晰

android - 决定在 firebase 中创建新项目或更新旧项目

android - Ubuntu,无法启动 react-native : Could not find tools. jar

android - 如何获取表格行/表格项的点击事件?

php - Laravel:从 android(不是浏览器)询问 "Am I Logged in?"

spring - 如何在 kotlin 中使用 spring 数据和 r2dbc 映射一个类