Reputation: 3215
I am trying to convert a timestamp to a day of the week.
The goal would be to translate to something like ts -> MON or TUE ....
I have tried the code below but it's not working.
fun convertToReadableDate(timestamp: Long): String {
val formatter = SimpleDateFormat("dd-mm-yyyy")
val cal = Calendar.getInstance(Locale.ENGLISH)
cal.timeInMillis = timestamp * 1000
val date: LocalDate = LocalDate.parse(formatter.format(cal.time))
return date.dayOfWeek.toString()
}
Any idea ? Thanks
Upvotes: 1
Views: 1586
Reputation: 977
get the day of the week from Unix timestamp:-
fun getDayOfWeek(timestamp: Long): String {
return SimpleDateFormat("EEEE", Locale.ENGLISH).format(timestamp * 1000)
}
getMonth:
fun getMonthFromTimeStamp(timestamp: Long): String {
return SimpleDateFormat("MMM", Locale.ENGLISH).format(timestamp * 1000)
}
getYear:
fun getYearFromTimeStamp(timestamp: Long): String {
return SimpleDateFormat("yyyy", Locale.ENGLISH).format(timestamp * 1000)
}
if you need all three combined in one function: (WED-MAY-2021)
fun getDayOfWeek(timestamp: Long): String {
return SimpleDateFormat("EEEE-MMM-yyyy", Locale.ENGLISH).format(timestamp * 1000)
}
if you need a combination of either of two in one function:(WED-MAY)
fun getDayOfWeek(timestamp: Long): String {
return SimpleDateFormat("EEEE-MMM", Locale.ENGLISH).format(timestamp * 1000)
}
Upvotes: 3
Reputation: 153
You can use this formatter:
fun convertToReadableDate(timestamp: Long): String =
SimpleDateFormat("EEE", Locale.ENGLISH).format(timestamp)
.toUpperCase(Locale.ENGLISH)
Upvotes: 0