a_local_nobody
a_local_nobody

Reputation: 8191

Why does Calendar.getDisplayName always return the same day of week when given milliseconds?

I'm trying to create an extension method to determine the name of the day within a week, given a specific Long value, so that it returns Monday, Tuesday, etc.

fun Long.convertFromLongToDayOfWeek(): String {

    val calendar = Calendar.getInstance()

    calendar.timeInMillis = this

    return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()) ?: ""
}

however, regardless of the value I pass to the calendar instance, it always returns "Monday".

I've written a few unit tests with Long values (which I receive from an API) and they all return Monday. Values to test with include the following:

This code is complete and inclusive up to here, the following unit tests are just there to simplify debugging:


   @Test
    fun testExample1() {

    val value: Long = 1601542800

    val result = value.convertFromLongToDayOfWeek()

    Assert.assertEquals("Monday", result)

    }

    @Test
    fun testExample2() {

    val value: Long = 1601715600

    val result = value.convertFromLongToDayOfWeek()

    Assert.assertEquals("Monday", result)

   }

both of these tests are passing, but neither of these Long values represent Monday, what am I doing wrong ?

Upvotes: 0

Views: 209

Answers (1)

cactustictacs
cactustictacs

Reputation: 19524

Those are all Mondays! They're actually all the same Monday, there's 86,400,000 milliseconds in a day, and those values are only a few hundred seconds apart

If you're getting timestamps in seconds from an API, you need to multiply them by 1000 to get millis (which is what the Calendar setter takes)

Upvotes: 2

Related Questions