2

How to get the timezone offset in UTC (like UTC+03:00) from Android device? I'm able to retrieve timezone offset in GMT format (which looks like GMT+03:00) with help of this code:

TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT)

by I can't to retrieve timezone offset in UTC format (what I want actually retrieve is something like UTC+03:00). How to achieve this?

UPD

It seems that it's something wrong with java.util.TimeZone class, because

val timeZoneGMT = TimeZone.getTimeZone("GMT")
Log.d("OLOLO ","Time zone GMT: " + timeZoneGMT.getDisplayName(false, TimeZone.SHORT))

outputs

Time zone GMT: GMT+00:00

but at the same time

val timeZone = TimeZone.getTimeZone("UTC")
Log.d("OLOLO ","Time zone UTC: " + timeZone.getDisplayName(false, TimeZone.SHORT))

outputs just this:

Time zone UTC: UTC

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ksenia
  • 3,453
  • 7
  • 31
  • 63
  • 1
    Solution for all android versions is addressed here https://stackoverflow.com/a/21349556/2199894 – Bassel Mourjan Nov 21 '18 at 12:01
  • @BasselMourjan, thanks, but this question about returning UTC time. And I need exactly UTC offset, rather than time in UTC format... – Ksenia Nov 21 '18 at 12:13
  • in that case another simple solution comes to mind.. string.replace() to replace GMT with UTC.. since both are the same – Bassel Mourjan Nov 21 '18 at 15:08

1 Answers1

0

Try this

Using java.time

    long timeNow = OffsetDateTime.now(ZoneOffset.UTC)
            .toEpochSecond();
    Log.d("Time ","Three years ago: " 
            + NumberFormat.getIntegerInstance().format(timeNow));

NOTE: for this your minimum API level must be 19 or above.

Using Calender

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

Log.d("Time ",sdf.format(calendar.getTime()));

NOTE:- This would work in all API level.

Hope it will solve your problem.

sushildlh
  • 8,986
  • 4
  • 33
  • 77