格林尼治标准​​时间转换日期时间字符串 [英] Convert GMT DateTime String

查看:129
本文介绍了格林尼治标准​​时间转换日期时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是pretty新的Java和我有点卡住使用的SimpleDateFormat 日历。我有约会对象,想提取GMT datestring像 YYYY-MM-DD HH:MM:SS 。我住在德国的那一刻,我们GMT +0200。我的约会对象的时间,例如 2011-07-18 13:00:00 。我现在需要的是 2011-07-18 11:00:00 。在我区偏移量应自动计算。

我想这样的事情,但我想有故障的地方:

 私人字符串toGmtString(日期为准){
    SimpleDateFormat的SD =新的SimpleDateFormat(YYYY-MM-DD HH:MM:SS);
    时区的timeZone = TimeZone.getDefault();
    日历CAL = Calendar.getInstance(新的SimpleTimeZone(timeZone.getOffset(date.getTime()),GMT));
    sd.setCalendar(CAL);
    返回sd.format(日期);
}

在某些设备就像我希望它返回datestring。在其他装置上的偏移不计算正确的,我接收来自输入日期对象的日期和时间。你能给我一些提示或建议?我想我的路要走获取默认时区不起作用?


解决方案

 私人字符串toGmtString(日期为准){
    SimpleDateFormat的SD =新的SimpleDateFormat(YYYY-MM-DD HH:MM:SS);
    sd.setTimeZone(TimeZone.getTimeZone(GMT));
    返回sd.format(日期);
}

您并不需要创建一个新的的SimpleTimeZone ,因为你没有发明一种新的时区 - 有一些开始发挥作用,在你的程序2现有的时区,格林尼治标准​​时间和你的默认值。

您也不必修改现有的约会对象,因为你不想再present在不同的时间点 - 你只需要以不同的方式来显示在同一时间点

所有你需要做的是告诉的SimpleDateFormat 的格式要使用的时区。

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?

解决方案

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.

这篇关于格林尼治标准​​时间转换日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆