Java 将时间对象 (GMT) 转换为字符串 (GMT+1)

标签 java time timezone simpledateformat

我尝试了以下代码,应该允许我将时间传递作为参数转换为一个多一小时 (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());
}    

有人知道怎么解决吗?

编辑:好的,最后我在我的 Controller 中创建了以下函数。
我在简单日期格式中设置的时区是客户端通过 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

最佳答案

代码似乎可以正常工作。当您输出结果时,时间显示为正确时区的时间。尝试按如下方式添加时区参数:

public static String getFormattedTimeLabel(final Time time, String tzId) {
  Calendar cal = new GregorianCalendar();
  cal.setTimeInMillis(time.getTime());
  SimpleDateFormat sdf = new SimpleDateFormat("HH : mm");
  sdf.setCalendar(cal);
  sdf.setTimeZone(tzId == null ? TimeZone.getDefault() : TimeZone.getTimeZone(tzId));
  return sdf.format(cal.getTime());
}

并将其调用为:

Time time = new Time(System.currentTimeMillis());
System.out.println(getFormattedTimeLabel(time, null));
System.out.println(getFormattedTimeLabel(time, "UTC"));

给出以下结果(截至目前):

12 : 08
11 : 08

因为我在 TZ GMT+1,现在刚过中午,结果是正确的。

顺便说一句,像这样打印时间对象:

System.out.println(time.toString());

给出:

12:08:16

即它在默认时区中默认格式化。

顺便说一句,该函数可以简化为不使用日历对象,如下所示:

public static String getFormattedTimeLabel(final Time time, String tzId) {
  SimpleDateFormat sdf = new SimpleDateFormat("HH : mm");
  sdf.setTimeZone(tzId == null ? TimeZone.getDefault() : TimeZone.getTimeZone(tzId));
  return sdf.format(time);
}

在 SimpleDateFormat 中设置时区就足够了。

关于Java 将时间对象 (GMT) 转换为字符串 (GMT+1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34589371/

相关文章:

java - 当路由器手动创建routee时,它们是如何通过监管策略重新启动的?

java - Android Studio AddView TableLayout,必须removeChild错误?

java - 流已被操作或关闭,尝试创建赛车手时获得异常

c++ - 我如何使用 tm 结构将分钟添加到当前时间?

java - 如何在 JDK 中手动更新时区?

java - 我已经创建了一个基本的 GUI,但按钮不会与文本字段交互

c++ - c++中两次时间的区别

date - 如何将毫秒转换为人类可读的形式?

javascript - Date() 在网站脚本中不考虑夏令时,但在 Firefox 控制台中执行时会考虑夏令时

linux - 在服务器 : Etc/UTC or Etc/Universal? 中设置哪个时区