Search code examples
androidkotlinlocalearabic

SimpleDateFormat from UTC Calendar Error when Locale is Arabic


I am attempting to convert a timestamp into a date, which I am then putting into the query parameters of a request.

Here is the function that converts a timestamp into a date:

override fun fromTimestamp(timestamp: Long): String {
    val tz = TimeZone.getTimeZone("UTC")
    val calendar = Calendar.getInstance(tz)
    calendar.timeInMillis = timestamp

    // Quoted "Z" to indicate UTC, no timezone offset
    val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    df.timeZone = tz

    return df.format(calendar.time)
}

This seems to work perfectly fine when my device is set in English, after URL encoding the date, this is what appears in the parameters: 1970-01-01T00%3A00%3A00.000Z

Now, if my device is set in Arabic, the URL encoded date looks like this: %D9%A2%D9%A0%D9%A1%D9%A8-%D9%A1%D9%A0-%D9%A1%D9%A7T%D9%A1%D9%A9%3A%D9%A4%D9%A7%3A%D9%A1%D9%A9.%D9%A0%D9%A8%D9%A2Z

I can only assume that all of those characters, that are suppose to be integers, that are encoded are Arabic characters depicting a date

After some googling, I found this discussion which says to initialize the Calendar with a Locale from the US. But looking at the code above, you notice the calendar is being initialized with a UTC timezone.

I would think that a calendar instanced from a UTC timezone would kick out integers instead of a specific language's characters depicting integers, but I'm not entirely sure how the Android system works with that.

Any idea on how I can modify my function to represent calendar dates with integers no matter what the Locale is?


Solution

  • My bet goes for

    SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)