【问题标题】:How to use "android.text.format.DateFormat" with Kotlin?如何在 Kotlin 中使用“android.text.format.DateFormat”?
【发布时间】:2021-10-01 16:55:55
【问题描述】:

    fun bind(crime: Crime){
            this.crime = crime
            titleTextView.text = this.crime.title
            val df : DateFormat = DateFormat.getInstance().format(DateFormat.LONG, DateFormat.MEDIUM)
            dateTextView.text = df.format(this.crime.date.toString())
            solvedImageView.visibility = if (crime.isSolved){
                View.VISIBLE
            }else{
                View.GONE
            }
        }

如何在 Kotlin 中使用日期格式库?

我想将此日期格式“Sun Jul 25 00:00:00 GMT+09:00 2021”更改为“Sun, Jul, 25, 2021”。

【问题讨论】:

  • 能否打印val df : DateFormat = DateFormat.getInstance().format(DateFormat.LONG, DateFormat.MEDIUM) dateTextView.text = df.format(this.crime.date.toString())的结果
  • @MohitAjwani 谢谢。但是,format() 函数没有这个参数。这条评论是由 android studio 向我展示的。 -------------------------------------------------- -------- 不能使用提供的参数调用以下函数。 format(Date!) 在 java.text.DateFormat 中定义 format(Date!, StringBuffer!, FieldPosition!) 在 java.text.DateFormat 中定义 format(Any!) 在 java.text.DateFormat 中定义 format(Any!, StringBuffer!, FieldPosition!) 在 java.text.DateFormat 中定义 ---------------------------------------- -----------------

标签: android kotlin


【解决方案1】:

您可以简单地使用以下内容:

val formattedDate = SimpleDateFormat("EE, MMM, dd, yyyy", Locale.US)
val date = formattedDate .parse(this.crime.date.toString())

【讨论】:

  • kotlin simpleDateFormat = SimpleDateFormat("EE, MMM, dd, yyyy", Locale.KOREA) val example : String = simpleDateFormat.format(this.crime.date).toString() dateTextView.text = example 此代码有效!谢谢
  • 太好了,我很高兴 :)
【解决方案2】:

检查 Java Docs 中的 DateFormatSimpleDateFormathttps://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

fun getTimeMillisFromString(dateValue: String, dateFormat: String): Long {
    val sdf = SimpleDateFormat(dateFormat)
    try {
        return sdf.parse(dateValue).time
    } catch (e: ParseException) {
        e.printStackTrace()
    }
}
return 0L

此函数将返回时间的长格式。您需要传递您收到的字符串和字符串的格式。比如getTimeMillisFromString("Sun Jul 25 00:00:00 GMT+09:00 2021", "yyyy.MM.dd HH:mm:ss z")

您可能需要将时区设置为 GMT,例如 sdf.setTimeZone(TimeZone.getTimeZone("GMT"))

获得长格式日期后,您可以使用SimpleDateFormat 将其转换为您想要的任何字符串格式。例如,

SimpleDateFormat(DATE_FORMAT_HYPHEN_DD_MM_YY, Locale.getDefault()).format(calender.time)

这应该会给你预期的字符串。

也检查这个答案SimpleDateFormat parse loses timezone

这也是更多信息Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

【讨论】:

  • 非常感谢。 !
  • 如果它对您有帮助,您可以为答案投票,以便其他人也可以在顶部看到它。
【解决方案3】:

您可以使用日历实例,然后通过 DAY_OF_WEEK YEAR MONTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-19
    • 2020-09-24
    • 2021-04-20
    • 1970-01-01
    • 2020-05-12
    • 2020-12-15
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多