Search code examples
kotlindatetimeutcdayofweekgmt

How to get day of the week of GMT using kotlin?


For EXAMPLE, current UTC time is:

17:14:24 UTC Friday, 5 November 2021

I want to get the result "6" (Sunday = 1 => Friday = 6)


Solution

  • Using kotlinx.datetime (which is multiplatform):

    import kotlinx.datetime.DayOfWeek
    import kotlinx.datetime.Instant
    import kotlinx.datetime.TimeZone
    import kotlinx.datetime.isoDayNumber
    import kotlinx.datetime.toLocalDateTime
    
    public val DayOfWeek.dayNumberStartingFromSunday: Int
        get() = when (this) {
            DayOfWeek.SUNDAY -> 1
            else -> isoDayNumber + 1
        }
    
    fun main() {
    //    val now: Instant = Clock.System.now()
        val now = Instant.parse("2021-11-05T17:14:24Z")
        val datetimeInUtc = now.toLocalDateTime(TimeZone.UTC)
        val dayNumberStartingFromSunday = datetimeInUtc.dayOfWeek.dayNumberStartingFromSunday
        println(dayNumberStartingFromSunday) // 6
    }