Seb
Seb

Reputation: 3215

convert timestamp to day of the week android

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

Answers (2)

Nitin Prakash
Nitin Prakash

Reputation: 977

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

Upvotes: 3

mosyonal
mosyonal

Reputation: 153

You can use this formatter:

fun convertToReadableDate(timestamp: Long): String = 
        SimpleDateFormat("EEE", Locale.ENGLISH).format(timestamp)
       .toUpperCase(Locale.ENGLISH)

Upvotes: 0

Related Questions