Good afternoon I want to convert my simpledateformat to show "Tuesday, 1st April" for example from "15/09/21", I was wondering how do I convert it to this? I have attached an image of what it looks like before.
My code calling the date:
addAll(pending.sortedByDescending { it.finishDate.convertToDate()?.time })
addAll(accepted.sortedByDescending { it.finishDate.convertToDate()?.time })
Where the time gets called:
fun String.convertToDate(): Date? {
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
return try {
sdf.parse(this)
} catch (e: ParseException) {
Timber.e("wrong date format - parsing not possible")
null
}
}
CodePudding user response:
try this
fun changedate(olddate:String):String{
var changedDate:String = ""
try {
val dateFormatprev = SimpleDateFormat("dd/MM/yyyy")
val d: Date = dateFormatprev.parse(olddate)
val dateFormat = SimpleDateFormat("EEE, MMM dd")
changedDate = dateFormat.format(d)
println(changedDate)
} catch (e: ParseException) {
e.printStackTrace()
}
return changedDate
}
usage
Log.e("TAG",changedate("01/01/2021"))
CodePudding user response:
SimpleDateFormat
is long outdated and troublesome, as suggested by @Ole V update to DateTimeFormatter
, Here's a sample code for same
DateTimeFormatter formatter = null;
String date = "2021-09-16T11:36:15";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("EEEE, MMM d"); // use MMMM to show full month name
Log.e("Date", "" dateTime.format(formatter2) );
}
To use this below android 8 , use desugaring
Output Thursday, Sep 16