21

I am new to Android and I am currently facing an issue to get current time given the timezone.

I get timezone in the format "GMT-7" i.e. string. and I have the system time.

Is there a clean way to get the current time in the above given timezone? Any help is appreciated. Thanks,

edit : Trying to do this :

public String getTime(String timezone) {
    Calendar c = Calendar.getInstance();
    c.setTimeZone(TimeZone.getTimeZone(timezone));
    Date date = c.getTime();
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    String strDate = df.format(date);
    return c.getTime().toString();
}
Flávio Faria
  • 6,575
  • 3
  • 39
  • 59
Vishesh Joshi
  • 1,601
  • 2
  • 16
  • 32
  • By “current time” you mean the time-of-day without a date, or did you mean a date-only as seen your example `SimpleDateFormat`, or did you mean a date-time as seen in that last line with `return`? – Basil Bourque Jul 12 '16 at 02:33

11 Answers11

24

I got it to work like this :

TimeZone tz = TimeZone.getTimeZone("GMT+05:30");
Calendar c = Calendar.getInstance(tz);
String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
            String.format("%02d" , c.get(Calendar.MINUTE))+":"+
.                   String.format("%02d" , c.get(Calendar.SECOND))+":"+
    .           String.format("%03d" , c.get(Calendar.MILLISECOND));

Also, every other time conversion based on this date should also be used with this timezone, otherwise, the default timezone of device will be used and the time will be converted based on that timezone.

Vishesh Joshi
  • 1,601
  • 2
  • 16
  • 32
  • How do you get an actual Date instead of a String? – Tulains Córdova May 02 '16 at 19:45
  • This will work only fro 5:30 time zone. What would be the solution if we want the app to pick the time zone specified in his phone settings? Like: If someone from Russia opens the app , he should get the Russian time zone. – Prince Bhatti Sep 17 '16 at 18:34
  • @COSTA you can use `TimeZone timeZone = TimeZone.getDefault();` to get the TimeZone of the location where your app is running. – Hammad Nasir Nov 14 '16 at 11:14
  • 5
    its returning the Device time, If user change the device time how can i get exact time from timeZone – Shashwat Gupta May 19 '17 at 11:46
  • @HammadNasir TimeZone.getDefault(); returns a string '+0530'. How can I format it as '+05:30' ? – KZoNE Mar 13 '19 at 04:51
  • @HammadNasir if that always the case you can do `TimeZome.getDefault().substring(0,3) + ":" + TimeZone.getDefault().substring(3);` – Zakaria M. Jawas Mar 16 '19 at 21:30
14
// Backup the system's timezone
TimeZone backup = TimeZone.getDefault();

String timezoneS = "GMT-1";
TimeZone tz = TimeZone.getTimeZone(timezoneS);
TimeZone.setDefault(tz);
// Now onwards, the default timezone will be GMT-1 until changed again

Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String timeS = String.format("Your time on %s:%s", timezoneS, date);
System.out.println(timeS);

// Restore the original timezone
TimeZone.setDefault(backup);
System.out.println(new Date());
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
aran
  • 10,978
  • 5
  • 39
  • 69
12

java.time

Both the older date-time classes bundled with Java and the third-party Joda-Time library have been supplanted by the java.time framework built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date. See Oracle Tutorial. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

By the way, never refer to an offset-from-UTC with a single digit of hours such as -7, as that is non-standard and will be incompatible with various protocols and libraries. Always pad with a zero for second digit, such as -07.

If all you have is an offset rather than a time zone, use the OffsetDateTime class.

ZoneOffset offset = ZoneOffset.ofHours( -7 );
OffsetDateTime odt = OffsetDateTime.now( offset );
String output1 = odt.toLocalTime().toString();
System.out.println( "Current time in " + offset + ": " + output1 );

Current time in -07:00: 19:41:36.525

If you have a full time zone, which is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST), rather than a mere offset-from-UTC, use the ZonedDateTime class.

ZoneId denverTimeZone = ZoneId.of( "America/Denver" );
ZonedDateTime zdt = ZonedDateTime.now( denverTimeZone );
String output2 = zdt.toLocalTime().toString();
System.out.println( "Current time in " + denverTimeZone + ": " + output2 );

Current time in America/Denver: 20:41:36.560

See this code in action in Ideone.com.

Joda-Time

You can use Joda-Time 2.7 in Android. Makes date-time work much easier.

DateTimeZone zone = DateTimeZone.forID ( "America/Denver" );
DateTime dateTime = new DateTime ( zone );
String output = dateTime.toLocalTime ().toString ();

dump to console.

System.out.println ( "zone: " + zone + " | dateTime: " + dateTime + " | output: " + output );

When run…

zone: America/Denver | dateTime: 2016-07-11T20:50:17.668-06:00 | output: 20:50:17.668

Count Since Epoch

I strongly recommend against tracking by time by count-since-epoch. But if necessary, you can extract Joda-Time’s internal milliseconds-since-epoch (Unix time, first moment of 1970 UTC) by calling the getMillis method on a DateTime.

Note the use of the 64-bit long rather than 32-bit int primitive types.

In java.time. Keep in mind that you may be losing data here, as java.time holds a resolution up to nanoseconds. Going from nanoseconds to milliseconds means truncating up to six digits of a decimal fraction of a second (3 digits for milliseconds, 9 for nanoseconds).

long millis = Instant.now ().toEpochMilli ();

In Joda-Time.

long millis = DateTime.now( denverTimeZone ).getMillis();
Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • How do I get this in milliseconds? – basickarl Mar 04 '15 at 19:13
  • @KarlMorrison Using a count of milliseconds is usually a bad idea (search StackOverflow for discussion), but if you insist see my edit. – Basil Bourque Mar 04 '15 at 21:56
  • @BasilBourque, thanks. But unfortunately, I am unable to get past `java.lang.IllegalArgumentException: The datetime zone id 'America/Denver' is not recognised` when I followed your code example. [This other answer](http://stackoverflow.com/questions/5451152/how-to-handle-jodatime-illegal-instant-due-to-time-zone-offset-transition) did not help either... – Narayana J Jul 12 '16 at 01:39
  • 1
    @NarayanaJ I just now copied-pasted in Joda-Time code that I just now ran in Java 8 with Joda-Time library 2.9.4. Also, you should know that the Joda-Time team advises migration to java.time classes. I added entire section at the top showing how to do the same work in java.time. You can exercise [that java.time code at Ideone.com](http://ideone.com/ZL8tSF). – Basil Bourque Jul 12 '16 at 02:54
  • 2
    Non of the above methods work if the device(mobile/system) time is wrong. How to get correct time thought system time is wrong? – Prashanth Debbadwar Nov 29 '16 at 06:46
  • 1
    @PrashanthDebbadwar Asked and answered many times on Stack Overflow such as [this](http://stackoverflow.com/q/2817475/642706) and [this](http://stackoverflow.com/q/31222397/642706) and [this](http://stackoverflow.com/q/32194245/642706). Please get in the habit of searching Stack Overflow, as it is intended to be more like Wikipedia and less like a discussion group. – Basil Bourque Nov 29 '16 at 07:25
9

Set the timezone to formatter, not calendar:

public String getTime(String timezone) {
    Calendar c = Calendar.getInstance();
    Date date = c.getTime(); //current date and time in UTC
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    df.setTimeZone(TimeZone.getTimeZone(timezone)); //format in given timezone
    String strDate = df.format(date);
    return strDate;
}
igork
  • 568
  • 7
  • 8
8

Try this:

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(TimeZone.getTimeZone("YOUR_TIMEZONE"));
String strDate = df.format(date);

YOUR_TIMEZONE may be something like: GMT, UTC, GMT-5, etc.

Flávio Faria
  • 6,575
  • 3
  • 39
  • 59
  • It doesn't work for me. I tried GMT+5 , GMT+7. but it keeps giving me current time in my timezone and not the one that I pass. – Vishesh Joshi Apr 24 '13 at 22:19
  • If you're planning to return `c.getTime().toString()` you don't need the DateFormat stuff. – Flávio Faria Apr 24 '13 at 22:29
  • Sorry, `c.getTime()` won't pass the timezone to the Date object. Try `c.toString()`. – Flávio Faria Apr 24 '13 at 22:31
  • 2
    You should refer to time zones by name rather than 3-letter codes or offset number. The 3-letter codes are not standardized, and many duplicates. If you use a name rather than an offset, your date-time library may assist with Daylight Saving Time and other anomalies. See [this list](http://joda-time.sourceforge.net/timezones.html) of names. – Basil Bourque Nov 28 '13 at 04:56
  • How do you get an actual Date instead of a String? – Tulains Córdova May 02 '16 at 19:46
5

Yes, you can. By call TimeZone setDefault() method.

public String getTime(String timezone) {
    TimeZone defaultTz = TimeZone.getDefault();

    TimeZone.setDefault(TimeZone.getTimeZone(timezone));
    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    String strDate = date.toString();

    // Reset Back to System Default
    TimeZone.setDefault(defaultTz);

    return strDate;
}
Tang Chanrith
  • 1,219
  • 12
  • 8
3

I found a better and simpler way.

First set time zone of app using

    TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));

And then call Calander to get date internally it uses default timezone set by above through out app.

     Calendar cal = Calendar.getInstance();
     Log.d("Los angeles time   ",cal.getTime().toString());

It will give current time based on time zone.

D/Los angeles time: Thu Jun 21 13:52:25 PDT 2018

Justcurious
  • 2,201
  • 1
  • 21
  • 36
1
 TimeZone tz = TimeZone.getTimeZone(TimeZoneID);
 Calendar c= Calendar.getInstance(tz);
 String time=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date(cal.getTimeInMillis()));

TimeZoneID can be one of from below as per as your choice

String[] ids=TimeZone.getAvailableIDs();

then time can be get as per accepted answer above

String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
            String.format("%02d" , c.get(Calendar.MINUTE))+":"+
                  String.format("%02d" , c.get(Calendar.SECOND))+":"+
               String.format("%03d" , c.get(Calendar.MILLISECOND));
Rajesh N
  • 6,198
  • 2
  • 47
  • 58
1

In Kotlin:

 val mTime: Calendar = Calendar.getInstance()
 val timeZone = TimeZone.getDefault().displayName // based on the device time zone it will calculate.

Output :

IST // it will return device time zone
Tippu Fisal Sheriff
  • 2,177
  • 11
  • 19
0

Cleanest way is with SimpleDateFormat

SimpleDateFormat = SimpleDateFormat("MMM\nd\nh:mm a", Locale.getDefault())

or you can specify the Locale

Kyle
  • 695
  • 6
  • 24
0

One way to deal with time zone and milliseconds values:

val currentDateTime = Calendar.getInstance().apply {
        timeZone?.let {
            val tzCalendar = Calendar.getInstance(it)
            this.set(Calendar.HOUR_OF_DAY, tzCalendar.get(Calendar.HOUR_OF_DAY))
            this.set(Calendar.MINUTE, tzCalendar.get(Calendar.MINUTE))
        }
    }.time

This way you're getting time in milliseconds for the specific timezone.

Goran Devs
  • 332
  • 3
  • 4