【问题标题】:Android Kotlin Convert date with Extensions fileAndroid Kotlin 使用扩展文件转换日期
【发布时间】:2021-10-19 10:45:23
【问题描述】:

我需要将String 格式的日期转换为星期四。 2021 年 9 月 23 日。,来自 Api。 Api 发送了许多日期,我希望将它们全部转换。 (带扩展文件) 怎么做?

【问题讨论】:

  • 使用gson库,可以将大部分(json API date)日期格式转换为java日期

标签: android date kotlin


【解决方案1】:

使用SimpleDateFormat

val date = SimpleDateFormat("dd/MM/yy").parse("31/11/2021");

这将产生您想要的输出。

即,1998 年 12 月 31 日星期四 00:00:00 IST

【讨论】:

    【解决方案2】:

    您可以将此代码 sn-p 用作 kotlin 扩展。

    fun Date.convertDate(dateString:String) : String{
         val inFormat = SimpleDateFormat("dd/MM/yy")
         var date: Date? = null
         try {
            date = inFormat.parse(dateString)
          } catch (e: ParseException) {
            e.printStackTrace()
          }
         val outFormat = SimpleDateFormat("dd MM, YYYY")
    
        return outFormat.format(date)
    
    }
    

    【讨论】:

    • published.text = model.publishedAt - publishedAt 是字符串
    • 如果我的日期(publishedAt)是字符串,我将如何使用这个扩展
    • 在任何类中添加扩展,然后像这样调用:published.text=Date().convertDate(model.publishedAt)
    • 错误 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“long java.util.Date.getTime()”
    • 在提供的扩展函数中,我们没有调用“java.util.Date.getTime()”。错误来自其他地方。
    猜你喜欢
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多