2

I need to get local time in my app. I am using Calendar class for this purpose.

Code :

Calendar calendar = Calendar.getInstance();

calendar.get(Calendar.HOUR_OF_DAY) shows the hours according to GMT.

I checked that TimeZone.getDefault().getDisplayName() shows GMT (which is incorrect) as default timezone but java.util.TimeZone.getDefault().getDisplayName() shows the correct timezone. Also calendar.getTime().toString() shows the correct time.

I do not understand why there is this discrepancy between android.icu.util.TimeZone and java.util.TimeZone

Edit:

I recently found that there are two Calendar APIs - java.util.Calendar (added in API level 1) and android.icu.util.Calendar (added in API level 24).

I had been using android.icu.util.Calendar but tested it on Android M. So now I'll be using API java.util.Calendar

arora
  • 21
  • 3
  • http://stackoverflow.com/questions/5369682/get-current-time-and-date-on-android – Nabin Aug 21 '16 at 11:49
  • @NabinKhadka I am getting time for GMT timezone. But my requirement is to get time for local timezone. – arora Aug 21 '16 at 15:59
  • you can use TimeZone.getDefault() it gives you default time zone and calendar instance by default picks default time zone – Aditi Aug 25 '16 at 10:58

2 Answers2

0

Have you tried the below:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+05:30")); //If you are seeking local time of India

Or

date.setTimeZone(TimeZone.getTimeZone("GMT+05:30")); 

String localTime = date.format(currentLocalTime); //To get current local time
deosha
  • 972
  • 5
  • 20
  • 1
    I need the timezone to be variable depending upon user's location. Android documentation suggests to use TimeZone.getDefault() for this purpose, but it is not working in my case. – arora Aug 21 '16 at 15:49
  • You can try long currentTime = new Date().getTime(); It will give time of the device. Hence, User's time in whichever zone he is – deosha Aug 24 '16 at 06:14
  • 1
    I'm completely unable to get the local time zone on any device i connect to Androids studio and use TimeZone.getDefault(). I always get GMT time with gmt Offset being 0. Anyone know how to get the real timezone in api 22 and above? – KuriaNdungu Mar 16 '17 at 06:34
0

Try this code:

String.format("GMT %.2f", TimeZone.getDefault()).replace(",", ".")

Also you can get the time zone that you want in this way:

TimeZone.getTimeZone("America/Los_Angeles");

For more details check documentation here: https://developer.android.com/reference/java/util/TimeZone