1

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

Seb
  • 2,929
  • 4
  • 30
  • 73

2 Answers2

2
  1. get the day of the week from Unix timestamp:-

     fun getDayOfWeek(timestamp: Long): String {
     return SimpleDateFormat("EEEE", Locale.ENGLISH).format(timestamp * 1000)
    

    }

  2. getMonth:

     fun getMonthFromTimeStamp(timestamp: Long): String {
     return SimpleDateFormat("MMM", Locale.ENGLISH).format(timestamp * 1000)
    

    }

  3. getYear:

     fun getYearFromTimeStamp(timestamp: Long): String {
     return SimpleDateFormat("yyyy", Locale.ENGLISH).format(timestamp * 1000)
    

    }

  4. 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)
     }
    
  5. 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)
     }
    
Nitin Prakash
  • 927
  • 9
  • 16
0

You can use this formatter:

fun convertToReadableDate(timestamp: Long): String = 
        SimpleDateFormat("EEE", Locale.ENGLISH).format(timestamp)
       .toUpperCase(Locale.ENGLISH)
mosyonal
  • 153
  • 1
  • 7