gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:53:31 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com