Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

date format - Getting GMT time with Android

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: 1o 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...