Get timezone android kotlin

Convert any string to timezone date and display in kotlin android

I am getting the date ( String ) in different formats from the API service. The date String maybe like «2010-10-15T09:27:37Z» or «July 30, 2020» or any other format. Now I need to convert that String to device timezone and based on the timezone country, the date and time should display accordingly on the UI. I tried the below:

 val today = LocalDate.now() println("localdate today " + today) val formattedToday = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)) println("formatted today" + formattedToday) 

But could anyone tell how to convert the String that is coming from API to device timezone format in android kotlin? Please help me with this issue. Thanks in advance.

2 Answers 2

The date String maybe like «2010-10-15T09:27:37Z» or «July 30, 2020» or any other format.

. is going to cause a lot of work. You will have to take care of a multitude of possible formats. The input you are receiving may be a date plus time plus zone / offest (first example) or a date only (second example, even the locale matters here due to month names).

For your first example ( «2010-10-15T09:27:37Z» ), a LocalDateTime is not a good choice because it would ignore the time zone or offset ( Z in this case for UTC or an offset of +00:00 hours).

For your second example ( «July 30, 2020» ), a LocalDate would be sufficient for parsing the String , but you will have to add a time and a zone / offset in order to show and convert it properly.

Use a ZonedDateTime or an OffsetDateTime along with ZoneId.systemDefault() to get the zone of the device.

Here’s an example for a ZonedDateTime including a possibility of converting from the current time zone into another (here «Europe/Amsterdam» , but you would obviously have to use ZoneId.systemDefault() then):

output of this example code:

2010-10-15T09:27:37Z is 2010-10-15T11:27:37+02:00[Europe/Amsterdam] in Amsterdam 2020-07-30T00:00Z[UTC] is 2020-07-30T02:00+02:00[Europe/Amsterdam] in Amsterdam 

Источник

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

But it always return me the timezone like » IST » but i want to get the timezone in GMT like this GMT+7:00.

It’s not the timezone in GMT, It’s called the offset from GMT. That may help you find the correct value.

@NaveenKumar If you know the IST, and GMT is always +05:30 hours. Then you always know the GMT too, right? But I guess that from Evert is better solution. (check my answer)

Читайте также:  Cv2 python install windows

FYI, an offset-from-UTC is a number of hours, minutes, and seconds – nothing more than that. A time zone is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a particular region.

23 Answers 23

This might give you an idea on how to implement it to your liking:

Calendar mCalendar = new GregorianCalendar(); TimeZone mTimeZone = mCalendar.getTimeZone(); int mGMTOffset = mTimeZone.getRawOffset(); System.out.printf("GMT offset is %s hours", TimeUnit.HOURS.convert(mGMTOffset, TimeUnit.MILLISECONDS)); 

(TimeUnit is «java.util.concurrent.TimeUnit»)

I would just point out that if you are looking for an exact offset including daylight savings you should use mTimeZone.getOffset(currentTime) instead.

This answer is not correct. rawOffset does not take daylight savings into account. To get the «real» offset you need: Calendar mCalendar = new GregorianCalendar(); TimeZone mTimeZone = mCalendar.getTimeZone(); int mGMTOffset = mTimeZone.getRawOffset() + (mTimeZone.inDaylightTime(new Date()) ? mTimeZone.getDSTSavings() : 0);

There are a number of cases where this will not work correctly. Summer time (DST) is one, another is when the offset is not a whole number of hours, as in the questioner’s time zone, for example. Also the classes Calendar , GregorianCalendar and TimeZone have later become long outdated and were always poorly designed. I recommend java.time, the modern Java date and time API.

This code return me GMT offset.

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault()); Date currentLocalTime = calendar.getTime(); DateFormat date = new SimpleDateFormat("Z"); String localTime = date.format(currentLocalTime); 

It returns the time zone offset like this: +0530

If we use SimpleDateFormat below

DateFormat date = new SimpleDateFormat("z",Locale.getDefault()); String localTime = date.format(currentLocalTime); 

It returns the time zone offset like this: GMT+05:30

Actually the first 2 lines are unnecessary. You can simply replace «currentLocalTime» with «new Date()» to get the current time (the Date object is just a timestamp and contains no locale information).

This is not working in Samsung s7 with Android 7.1(nougat) It retunrs IST not GMT+05:30 Its working fine in lower version.

Here is a solution to get timezone offset in GMT+05:30 this format

public String getCurrentTimezoneOffset() < TimeZone tz = TimeZone.getDefault(); Calendar cal = GregorianCalendar.getInstance(tz); int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60)); offset = "GMT"+(offsetInMillis >= 0 ? "+" : "-") + offset; return offset; > 

You can replace the first 3 lines with: int offsetInMillis = TimeZone.getDefault(System.currentTimeMillis());

a one line solution is to use the Z symbol like:

new SimpleDateFormat(pattern, Locale.getDefault()).format(System.currentTimeMillis()); 
public static String timeZone()

returns like +03:30

This is how Google recommends getting TimezoneOffset.

Calendar calendar = Calendar.getInstance(Locale.getDefault()); int offset = -(calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000) 
public static String getCurrentTimezoneOffset() < TimeZone tz = TimeZone.getDefault(); Calendar cal = GregorianCalendar.getInstance(tz); int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60)); offset = (offsetInMillis >= 0 ? "+" : "-") + offset; return offset; > 
 TimeZone tz = TimeZone.getDefault(); Calendar cal = GregorianCalendar.getInstance(tz); int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60)); offset = (offsetInMillis >= 0 ? "+" : "-") + offset; 

Yet another solution to get timezone offset:

TimeZone tz = TimeZone.getDefault(); String current_Time_Zone = getGmtOffsetString(tz.getRawOffset()); public static String getGmtOffsetString(int offsetMillis) < int offsetMinutes = offsetMillis / 60000; char sign = '+'; if (offsetMinutes < 0) < sign = '-'; offsetMinutes = -offsetMinutes; >return String.format("GMT%c%02d:%02d", sign, offsetMinutes/60, offsetMinutes % 60); > 

this is acually wrong as getRawOffset() returns offset from -8 UTC, not from UTC: developer.android.com/reference/java/util/TimeZone.html

TimeZone timeZone = TimeZone.getDefault(); String timeZoneInGMTFormat = timeZone.getDisplayName(false,TimeZone.SHORT); 

Generally you cannot translate from a time zone like Asia/Kolkata to a GMT offset like +05:30 or +07:00. A time zone, as the name says, is a place on earth and comprises the historic, present and known future UTC offsets used by the people in that place (for now we can regard GMT and UTC as synonyms, strictly speaking they are not). For example, Asia/Kolkata has been at offset +05:30 since 1945. During periods between 1941 and 1945 it was at +06:30 and before that time at +05:53:20 (yes, with seconds precision). Many other time zones have summer time (daylight saving time, DST) and change their offset twice a year.

Читайте также:  Поле с паролем

Given a point in time, we can make the translation for that particular point in time, though. I should like to provide the modern way of doing that.

java.time and ThreeTenABP

 ZoneId zone = ZoneId.of("Asia/Kolkata"); ZoneOffset offsetIn1944 = LocalDateTime.of(1944, Month.JANUARY, 1, 0, 0) .atZone(zone) .getOffset(); System.out.println("Offset in 1944: " + offsetIn1944); ZoneOffset offsetToday = OffsetDateTime.now(zone) .getOffset(); System.out.println("Offset now: " + offsetToday); 

Output when running just now was:

Offset in 1944: +06:30 Offset now: +05:30 

For the default time zone set zone to ZoneId.systemDefault() .

To format the offset with the text GMT use a formatter with OOOO (four uppercase letter O) in the pattern:

 DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("OOOO"); System.out.println(offsetFormatter.format(offsetToday)); 

I am recommending and in my code I am using java.time, the modern Java date and time API. The TimeZone , Calendar , Date , SimpleDateFormat and DateFormat classes used in many of the other answers are poorly designed and now long outdated, so my suggestion is to avoid all of them.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Читайте также:  Javascript onload function in div

Источник

How to get the current time of device android depending on the region with Kotlin?

nothing. What you get is the local time. And you don’t need .toString the t since t is already a String.

As an aside consider throwing away the long outmoded and notoriously troublesome SimpleDateFormat and friends. See if you either can use desugaring or add ThreeTenABP to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with.

2 Answers 2

You don’t have to change anything, the code gives you the device’s current time

However, since it may not be accurate for each device, it is recommended to receive it from the server in case of time.

Your code is implicitly using the JVM’s default time zone. This doesn’t seem to give you the result that you wanted. The solution is to specify time zone explicitly (which is usually a good idea anyway).

java.time

I am using java.time, the modern Java date and time API.

 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"); ZoneId usersDesiredTimeZone = ZoneId.of("Africa/Tripoli"); ZonedDateTime now = ZonedDateTime.now(usersDesiredTimeZone); String text = now.format(formatter); System.out.println(text); 

When I ran this snippet just now, the output was:

The time printed is 2 hours ahead of UTC because this is what Libya is using. Please substitute your own desired time zone.

Yet another change from your code is I am using uppercase HH for hour of day from 00 through 23 in the format pattern string. Lowercase hh is for hour within AM or PM from 01 through 12. I figured this was probably not what you had wanted.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • Java 8+ APIs available through desugaring
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Источник

Оцените статью