Convert GMT DateTime String

混江龙づ霸主 提交于 2019-12-23 11:47:33

问题


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?


回答1:


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.




回答2:


private String toGmtString(Date date){
    //date formatter
    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //getting default timeZone
    TimeZone timeZone = TimeZone.getDefault();
    //getting current time
    Calendar cal = Calendar.getInstance()
    cal.setTime(date) ;
    //adding / substracting curren't timezone's offset
    cal.add(Calendar.MILLISECOND, -1 * timeZone.getRawOffset());    
    //formatting and returning string of date
    return sd.format(cal.getTime());
}


来源:https://stackoverflow.com/questions/6730797/convert-gmt-datetime-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!