0

I have a simple code where i want to convert a certain given time to another time zone , in my case the time is local to UK , but i need to convert the time to another timezone if the user lives in different country , i have tried this simple code but it is not working for me , it is giving me random hour 04:00 any help would be appreciated guys

  • This is the code

        var localTime = "16:00" // simulating time to Uk timezone
        localtime.text = localTime

        timeZone.setOnClickListener {
            val localTimes = "16:00"
            val timeFormatter = SimpleDateFormat("hh:mm", Locale.UK)
            val timezone = TimeZone.getDefault() // get device timezone
            timeFormatter.timeZone = timezone
            val timeToFormat = timeFormatter.parse(localTimes)
            val formattedTime = timeFormatter.format(timeToFormat)
            localtime.text = formattedTime
        }

Taki
  • 3,290
  • 1
  • 16
  • 41
  • `hh:mm` date format is used for the 12 hour format, so this is why you get the 4:00. Try `HH:mm` instead, if you'd like to achieve 24 hour format. – Rafal Nov 06 '20 at 04:49
  • i guess it is actually taking the hour 16:00 and converting it to 12h format but the hour not changing – Taki Nov 06 '20 at 05:29
  • This is because you're using the default timezone, isn't it? If your goal is to use specific timezone then try something like: `timeFormatter.timeZone = TimeZone.getTimeZone("Europe/London")`. Take a look here: https://stackoverflow.com/questions/62929417/kotlin-simpledateformat-parse-wrong-timezone – Rafal Nov 07 '20 at 06:52

0 Answers0