I'm trying to convert a UTC string date to local time, so it's in a more readable format. I have a textView that in my activity layout:

<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" />

In my 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

The publishedAt string is in this format from the api call "2018-12-10T19:48:39Z". How can I convert this ZULU time format to local time?

推荐答案

try 使用扩展函数

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)
}

Usage:

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

Output: "11 Sep 2018"

Kotlin相关问答推荐

如何确保Kotlin子类已完成初始化?

为什么 Kotlin 中没有 init 块的注释

顶级属性的初始化

Kotlin 使用委托进行隐式覆盖

kotlin 如何决定 lambda 中的参数名称?

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

compareBy 如何使用布尔表达式在 kotlin 中工作

从字符串列表构建字符串

在 Kotlin 中,当枚举类实现接口时,如何解决继承的声明冲突?

Kotlin 和 Java 字符串拆分与正则表达式的区别

jetpack compose 将参数传递给 viewModel

Gradle 同步失败:不支持的方法:KotlinPlatformContainer.supports()

Kotlin 有 array.indexOf 但我无法弄清楚如何做 array.indexOfBy { lambda }

将多个 Kotlin 流合并到一个列表中,而无需等待第一个值

如何使用kotlin中的反射查找包中的所有类

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

在 gradle android library kotlin 项目中禁用 META-INF/* 生成

Gradle:无法连接到 Windows 上的 Kotlin 守护程序

使用 kotlin 每 3 位数添加逗号或点

访问Kotlin中的属性委托