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.

Community
  • 1
  • 1
Dayerman
  • 3,973
  • 6
  • 38
  • 54

6 Answers6

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!

Parag Chauhan
  • 35,760
  • 13
  • 86
  • 95
nithinreddy
  • 6,167
  • 4
  • 38
  • 44
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.

Parag Chauhan
  • 35,760
  • 13
  • 86
  • 95
Vade
  • 2,009
  • 6
  • 24
  • 32
  • Should I get currentLocaltime using String localTime = date.format(new Date()); right?? – Dayerman May 16 '11 at 10:07
  • 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 luck – Dayerman May 16 '11 at 10:13
  • 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 ok – Vade May 16 '11 at 10:17
  • 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. – Dayerman May 16 '11 at 10:25
  • @ 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:30 – Vade May 16 '11 at 10:31
  • 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. – Dayerman May 16 '11 at 10:39
  • @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? – Vade May 16 '11 at 10:48
  • Thanks Vade. In Spain current UTC is GMT +2 for summer, GMT + 1 rest of year – Dayerman May 16 '11 at 11:00
  • 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 ;) – Dayerman May 16 '11 at 11:07
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

Giora
  • 74
  • 1
  • 7
    -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 better – Patrick May 08 '15 at 10:01
  • @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. – Ole V.V. Mar 30 '20 at 19:26
  • 1
    @OleV.V. Fair enough, not super intuitive, but the javadoc clearly agrees with your statement – Patrick Mar 31 '20 at 13:57
  • @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](https://stackoverflow.com/a/60936711/5772882) shows a way to avoid using that class altogether. – Ole V.V. Mar 31 '20 at 16:06
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();
alexm
  • 1,285
  • 18
  • 36
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.

Ramdhas
  • 1,765
  • 1
  • 18
  • 26
  • 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? – Dr. Failov Jul 02 '17 at 10:09
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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161