简体   繁体   English

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

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

I am getting json response in date format 2022-03-25T00:00:00.000ZI want get day, month and year seperately and attach in text view in recycler view kotlin.我收到日期格式为 2022-03-25T00:00:00.000ZI 的 json 响应我想分别获取日、月和年,并附加到回收器视图 kotlin 的文本视图中。

Try this尝试这个

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

Please check -I have added separated value you can use as per your requirements.请检查 - 我已经添加了您可以根据您的要求使用的单独值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM