Getting GMT time with Android
Asked Answered
M

6

16

I have been digging into the question for a while in StackOverflow Android get Current UTC time and How can I get the current date and time in UTC or GMT in Java?

I have tried two ways to get the current time of my phone in GMT. I am in Spain and the difference is GMT+2. So let's see with an example: 1º attemp: I created a format and applied it to System.currentTimeMillis();

    DateFormat dfgmt = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");   
    dfgmt.setTimeZone(TimeZone.getTimeZone("GMT")); 
    String gmtTime = dfgmt.format(new Date());
    //Using System.currentTimeMillis() is the same as new Date()
    Date dPhoneTime = dfgmt.parse(gmtTime);
    Long phoneTimeUTC = dPhoneTime.getTime();

I need to substract that time to another time, that's why i do the cast to Long.

    DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");          
    Date arrivalDate = df.parse(item.getArrivalDate());
    //the String comes from JSON and is for example:"UTC_arrival":"2011-05-16 18:00:00"
    //which already is in UTC format. So the DateFormat doesnt have the GMT paramater as dfgmt
    diff = arrival.getTime() - phoneTimeUTC ;

I also tried this:

    Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()

And still I dont get the right difference. But if I do this:

    Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()-3600000*2;

It does work OK.

Any ideas?

Thanks a lot,

David.

Mandiemandingo answered 16/5, 2011 at 8:43 Comment(0)
A
5

As far as I read the calendar.getTimeInMillis(); returns the UTC time in millis. I used the following code and compared it to the Epoch in this site http://www.xav.com/time.cgi.

public int GetUnixTime()
{
    Calendar calendar = Calendar.getInstance();
    long now = calendar.getTimeInMillis();
    int utc = (int)(now / 1000);
    return (utc);

}

Giora

Ameeameer answered 31/5, 2011 at 7:7 Comment(4)
-1: getInstance() clearly states: "Constructs a new instance of the Calendar subclass appropriate for the default Locale and default TimeZone.". Probably Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() will work betterOtoplasty
@patrickf The time zone of the Calendar doesn’t matter (not only because no wise programmers are using Calendar anymore) also because getTimeInMillis() returns the same millisecond count regardless of time zone.Banger
@OleV.V. Fair enough, not super intuitive, but the javadoc clearly agrees with your statementOtoplasty
@patrickf The real problem/source of confusion is the poor design of the Calendar class, there’s way too much responsibility stuffed into one class, among other problems. My answer shows a way to avoid using that class altogether.Banger
A
26

This works for sure!

        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
        System.out.println(dateFormatGmt.format(new Date())+"");

Specify the format, and you will get it in GMT!

Algorism answered 17/4, 2012 at 6:37 Comment(0)
L
5
     Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
     Date currentLocalTime = cal.getTime();
     DateFormat date = new SimpleDateFormat("dd-MM-yyy HH:mm:ss z");   
     date.setTimeZone(TimeZone.getTimeZone("GMT")); 
     String localTime = date.format(currentLocalTime); 
     System.out.println(localTime);

Have a look and see if that works.

Lutero answered 16/5, 2011 at 8:56 Comment(9)
Should I get currentLocaltime using String localTime = date.format(new Date()); right??Mandiemandingo
I have used this 'code' DateFormat dfgmt = new java.text.SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z"); dfgmt.setTimeZone(TimeZone.getTimeZone("GMT")); String gmtTime = dfgmt.format(new Date().getTime()); Date dPhoneTime = dfgmt.parse(gmtTime); Long phoneTime = dPhoneTime.getTime(); 'code' and still no luckMandiemandingo
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.add(Calendar.SECOND, 0); Date currentLocalTime = cal.getTime(); DateFormat date = new SimpleDateFormat("dd-MM-yyy HH:mm:ss z"); date.setTimeZone(TimeZone.getTimeZone("GMT")); String localTime = date.format(currentLocalTime); System.out.println(localTime); I just ran this and it seems to work fine for me, i am in the UK so i changed it to EST to test and it seems okLutero
Hello Vade, I am not looking for the localTime but for the UTC time.If at Spain is now 12.25, I want to get 10.25. with your code I am still getting the localtime.Mandiemandingo
@ Dayerman, sorry i am little confused by what you mean, the code above (edited reply) returns on my computer the current GMT or UTC -0 time. I have tried several times to adjust my computers time zone to utc+3 or utc-2 each time i run the code it still returns the correct GMT time. for example currently in the uk (daylight saving) is 11:30 so utc = 10:30 if i change time to utc+3 it becomes 14:30 but still running that code returns 10:30Lutero
Hello Vade, I still cant get the UTC time, but I have two more lines , to get the milliseconds, that might change the time to local time.'code' Date dPhoneTimeUTC = dfgmt.parse(localTime); Long phoneTime = dPhoneTimeUTC.getTime(); 'code' And also, I am running the code on my phone, but I guess is the same than in a computer.Mandiemandingo
@dayerman i am off for lunch with the wife in 5 mins, when i get back if you havent found a solutions ill whack my android into my pc and knock up a quick app to test it out. but as far as i can tell it should work fine on both. you are aware that the current UTC time is GMT -1?Lutero
Thanks Vade. In Spain current UTC is GMT +2 for summer, GMT + 1 rest of yearMandiemandingo
It would be great if you can do the test as I am doing. E.g. you have an String with 30min ahead of localtime in UTC for example now is 13.00 GMT+2(in your case 12.00 GMT-1) so you have a String date = 2011-05-19 11:30:00, parse it, and then you get the currentTime from the phone(11:00 UTC), pass to UTC and diff = date - phoneUTC = 30 min. If you can get that it would be brilliant ;)Mandiemandingo
A
5

As far as I read the calendar.getTimeInMillis(); returns the UTC time in millis. I used the following code and compared it to the Epoch in this site http://www.xav.com/time.cgi.

public int GetUnixTime()
{
    Calendar calendar = Calendar.getInstance();
    long now = calendar.getTimeInMillis();
    int utc = (int)(now / 1000);
    return (utc);

}

Giora

Ameeameer answered 31/5, 2011 at 7:7 Comment(4)
-1: getInstance() clearly states: "Constructs a new instance of the Calendar subclass appropriate for the default Locale and default TimeZone.". Probably Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() will work betterOtoplasty
@patrickf The time zone of the Calendar doesn’t matter (not only because no wise programmers are using Calendar anymore) also because getTimeInMillis() returns the same millisecond count regardless of time zone.Banger
@OleV.V. Fair enough, not super intuitive, but the javadoc clearly agrees with your statementOtoplasty
@patrickf The real problem/source of confusion is the poor design of the Calendar class, there’s way too much responsibility stuffed into one class, among other problems. My answer shows a way to avoid using that class altogether.Banger
G
4

you can always use:

Calendar mCalendar = Calendar.getInstance(TimeZone.getTimeZone("gmt"));
long millies = mCalendar.getTimeInMillis();

or

Calendar mCalendar = Calendar.getInstance(TimeZone.getTimeZone("utc"));
long millies = mCalendar.getTimeInMillis();
Galvanoscope answered 4/7, 2014 at 23:35 Comment(0)
D
1

Output: 2016-08-01 14:37:48 UTC

    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

Works fine.

Delative answered 3/8, 2016 at 9:24 Comment(1)
But how system will know from which timezone my Date object is? What if I want to convert Date from +2 timezone to GMT, or vise versa?Troublous
B
1

java.time and ThreeTenABP

I am providing the modern answer.

To get the difference in milliseconds between the phone time now — in Spain or any other place — and a certain time in the past:

    // Example arrival time for the demonstration
    Instant arrival = Instant.parse("2020-02-29T12:34:56.789Z");
    Instant currentTime = Instant.now();
    long difference = ChronoUnit.MILLIS.between(arrival, currentTime);
    System.out.println("Difference is " + difference + " milliseconds");

Example output:

Difference is 2610350731 milliseconds

If you want the difference in seconds or some other time unit, just use the appropriate enum constant from the ChronoUnit enum instead of ChronoUnit.MILLIS.

There is no need to worry about the device time zone, nor about formatting or parsing the time, those worries only lead to over-complication of this basically simple matter.

BTW the epoch is one well-defined point in time, it doesn’t vary with time zone, it’s the same all over the world. Therefore the count of milliseconds from the epoch till now is also the same in all time zones. Some say that this count is always in UTC because the epoch is (usually) defined in UTC, as January 1, 1970 at 00:00 UTC.

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 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.

Links

Banger answered 30/3, 2020 at 18:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.