Mar*_*rco 5 java android date gmt simpledateformat
我是Java的新手,我对使用SimpleDateFormat和使用时有点困惑Calendar.我有一个Date-Object,想要提取GMT日期字符串yyyy-MM-dd HH:mm:ss.我住在德国,目前我们是GMT +0200.我的Date-Object的时间就是例如2011-07-18 13:00:00.我现在需要的是2011-07-18 11:00:00.我的时区的偏移量应自动计算.
我试过这样的事情,但我想某处有一个错误:
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);
}
Run Code Online (Sandbox Code Playgroud)
在某些设备上,datetring会像我想要的那样返回.在其他设备上,偏移量未正确计算,我从输入日期 - 对象接收日期和时间.你能给我一些提示或建议吗?我想我的方式获得默认时区不起作用?
private String toGmtString(Date date){
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sd.setTimeZone(TimeZone.getTimeZone("GMT"));
return sd.format(date);
}
Run Code Online (Sandbox Code Playgroud)
你不需要创建一个新的SimpleTimeZone,因为你没有发明一个新的时区 - 你的程序中有2个现有的时区,GMT和你的默认时区.
您也不需要修改现有的日期对象,因为您不希望表示不同的时间点 - 您只需要一种不同的方式来显示相同的时间点.
您需要做的就是告诉SimpleDateFormat格式化时使用哪个时区.
| 归档时间: |
|
| 查看次数: |
9944 次 |
| 最近记录: |