如何从 json 响应中获取日期并通过提取日期、月份、年份附加到 recyclerView 适配器并附加到 textview

How to get date from json response and attached to recycleView Adapter by extracting date,month,year and attach to textview

我收到 json 日期格式的响应 2022-03-25T00:00:00.000Z 我想分别获取日、月和年,并在回收器视图 kotlin 的文本视图中附加。

试试这个

convertFormatOfDate(
"2022-03-25T00:00:00.000Z",
                "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
                "MMMM dd, yyyy"  //You will get Month,Day and Year here ..
            )



fun convertFormatOfDate(
        dateString: String,
        currentFormat: String,
        desiredFormat: String
    ): String {
        val currentSdf = SimpleDateFormat(currentFormat, Locale.getDefault())
        val currentDate: Date? = currentSdf.parse(dateString)
        val desiredSdf = SimpleDateFormat(desiredFormat, Locale.getDefault())
        return desiredSdf.format(currentDate!!)
    }

请检查 - 我已经添加了您可以根据需要使用的分隔值。

    val str = convertFormatOfDate(
                "2022-03-25T00:00:00.000Z",
                "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
                "MMMM, dd, yyyy"  //You will get Month,Day and Year here ..
            )
  //OPTION 1
            val out = str.split(",")
            println("Year = " + out[2].chars())
            println("Month = " + out[0].chars())
            println("Day = " + out[1].chars())
    //OPTION 2
            val f: DateTimeFormatter = DateTimeFormatter.ofPattern("MMMM, dd, yyyy")
            val ld: LocalDate = LocalDate.parse(str, f)
            val year = ld.year
            val month = ld.month
            val dayOfMonth = ld.dayOfMonth
    
            Log.e("year", year.toString())
            Log.e("month", month.toString())
            Log.e("dayOfMonth", dayOfMonth.toString())
    
        }
    
        private fun convertFormatOfDate(
            dateString: String,
            currentFormat: String,
            desiredFormat: String
        ): String {
            val currentSdf = SimpleDateFormat(currentFormat, Locale.getDefault())
            val currentDate: Date? = currentSdf.parse(dateString)
            val desiredSdf = SimpleDateFormat(desiredFormat, Locale.getDefault())
            return desiredSdf.format(currentDate!!)
        }