gpt4 book ai didi

java - 如何使用 Java 处理日历时区?

转载 作者:IT老高 更新时间:2023-10-28 11:33:14 25 4
gpt4 key购买 nike

我有一个来 self 的应用程序的时间戳值。用户可以在任何给定的本地时区。

由于此日期用于假定给定时间始终为 GMT 的 WebService,因此我需要将用户参数从 (EST) 转换为 (GMT)。这是踢球者:用户忘记了他的 TZ。他输入了他想发送给 WS 的创建日期,所以我需要的是:

用户输入: 2008 年 5 月 1 日下午 6:12(美国东部标准时间)
WS 的参数需要是:5/1/2008 6:12 PM (GMT)

我知道默认情况下 TimeStamps 总是应该在 GMT 中,但是在发送参数时,即使我从 TS(应该在 GMT 中)创建了我的日历,除非用户是在格林威治标准时间。我错过了什么?

Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
...
private static java.util.Calendar convertTimestampToJavaCalendar(Timestamp ts_) {
java.util.Calendar cal = java.util.Calendar.getInstance(
GMT_TIMEZONE, EN_US_LOCALE);
cal.setTimeInMillis(ts_.getTime());
return cal;
}

使用之前的代码,这是我得到的结果(便于阅读的短格式):

[2008 年 5 月 1 日晚上 11:12]

最佳答案

public static Calendar convertToGmt(Calendar cal) {

Date date = cal.getTime();
TimeZone tz = cal.getTimeZone();

log.debug("input calendar has date [" + date + "]");

//Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
long msFromEpochGmt = date.getTime();

//gives you the current offset in ms from GMT at the current date
int offsetFromUTC = tz.getOffset(msFromEpochGmt);
log.debug("offset is " + offsetFromUTC);

//create a new calendar in GMT timezone, set to this date and add the offset
Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.setTime(date);
gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);

log.debug("Created GMT cal with date [" + gmtCal.getTime() + "]");

return gmtCal;
}

如果我通过当前时间(来自 Calendar.getInstance() 的“12:09:05 EDT”),输出如下:

DEBUG - input calendar has date [Thu Oct 23 12:09:05 EDT 2008]
DEBUG - offset is -14400000
DEBUG - Created GMT cal with date [Thu Oct 23 08:09:05 EDT 2008]

格林威治标准时间 12:09:05 是美国东部时间 8:09:05。

这里令人困惑的部分是 Calendar.getTime() 在您当前的时区中返回一个 Date,并且没有任何方法可以修改日历并滚动基础日期。根据您的 Web 服务采用哪种类型的参数,您可能只想让 WS 以从纪元开始的毫秒数为单位进行处理。

关于java - 如何使用 Java 处理日历时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/230126/

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