I am getting json response in date format 2022-03-25T00:00:00.000Z I want get day , month and year seperately and attach in text view in recycler view kotlin.
CodePudding user response:
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!!)
}
CodePudding user response:
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!!)
}