Convert GMT DateTime String

Marco picture Marco · Jul 18, 2011 · Viewed 10.3k times · Source

I am pretty new to Java and I am a little stuck with using SimpleDateFormat and Calendar. I have a Date-Object and want to extract a GMT datestring like yyyy-MM-dd HH:mm:ss. I live in Germany and at the moment we are GMT +0200. My Date-Object's time is for example 2011-07-18 13:00:00. What I need now is 2011-07-18 11:00:00. The offset for my timezone should be calculated automatically.

I tried something like this, but I guess there is a fault somewhere:

private String toGmtString(Date date){
    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    TimeZone timeZone = TimeZone.getDefault();
    Calendar cal = Calendar.getInstance(new SimpleTimeZone(timeZone.getOffset(date.getTime()), "GMT"));
    sd.setCalendar(cal);
    return sd.format(date);
}

On some devices the datestring is returned like I want it to. On other devices the offset isn't calculated right and I receive the date and time from the input date-object. Can you give me some tips or advices? I guess my way off getting the default timezone does not work?

Answer

Eli Acherkan picture Eli Acherkan · Jul 18, 2011
private String toGmtString(Date date){
    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sd.setTimeZone(TimeZone.getTimeZone("GMT"));
    return sd.format(date);
}

You don't need to create a new SimpleTimeZone, because you aren't inventing a new timezone - there are 2 existing timezones that come into play in your program, GMT and your default one.

You also don't need to modify your existing date object, because you don't want to represent a different point in time - you only want a different way to display the same point in time.

All you need to do is tell the SimpleDateFormat which timezone to use in formatting.