【发布时间】:2016-04-07 23:03:20
【问题描述】:
我尝试了以下代码,它应该允许我将时间传递作为参数转换为一个多小时 (GMT+1) 的字符串。
但我总是得到与我的对象时间相同的时间
public static String getFormattedTimeLabel(final Time time) {
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(time.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("HH : mm");
sdf.setCalendar(cal);
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(cal.getTime());
}
有人知道怎么解决吗?
编辑:好的,最后我在控制器中创建了以下函数。
由于 HttpServletRequest,我以简单日期格式设置的时区是客户端恢复的时区。
代码后可以看到 System.out 的打印结果。
private Time getTimeLocal(Time requestTime) {
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(requestTime.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("HH : mm");
sdf.setCalendar(cal);
System.out.println(requestTime);
sdf.setTimeZone(tz);
System.out.println(tz.getID());
String dt = sdf.format(cal.getTime());
Date date = null;
try {
date = sdf.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(dt);
return new Time(date.getTime());
}
10:00:00 //the Time object
Europe/Paris // The id of the client timezone (GMT+1 for me)
10 : 00 //the date. the time printed is not correct it should be set with the timezone of the client so for me GMT+1 so 11:00:00
【问题讨论】:
-
@BoristheSpider TimeZone.getDefault() 应该是系统的时区。而且我不使用我想要的那个,因为它可能会根据使用应用程序的国家/地区而有所不同
-
@Spidi'sWeb:问题不在于增加小时数,而在于设置时区和格式。
-
@BoristheSpider 我从数据库中获得的时间,我没有打印它,但通常如果我用 Timezone.getDefault() 格式化它,我应该有这个时间 + 1 小时因为我在巴黎。问题是最后没有添加小时
-
@JeromeCampeaux 我明白了——数据库让事情变得更加复杂。数据如何存储在数据库中,数据库设置为哪个时区? JDBC 连接到数据库的时区是什么?我问是因为 JDBC 有进行自动转换的讨厌习惯...我建议您在收到数据时打印数据,看看 JDBC 对您造成了什么样的影响。
标签: java time timezone simpledateformat