所以我将时间戳保存为Date
个对象,将时区保存为TimeZone
个对象。
现在我想创建一个以Date
对象和TimeZone
对象作为参数的函数,并返回使用时间戳调整的Date
对象。
例如:
输入:
Date TimeZone 12:00 Moscow Standard Time (UTC+3)
输出:
Date 3:00
修改
删除了关于Calendar
答案 0 :(得分:7)
java.util.Date
是绝对时间点。 0900小时UTC 和 1200小时UTC + 3 是完全相同的java.util.Date
对象。为了代表一个或另一个,没有“调整”。
要获得特定时区的人类可读表示,您可以在DateFormat
对象上设置时区。
DateFormat format = new SimpleDateFormat("HH:mm");
format.setTimeZone(TimeZone.getTimeZone("UTC+3"));
String time = format.format(yourDate);
评论中提出的问题的解决方案:
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC+3"));
cal1.setTime(yourDate);
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal2.clear();
cal2.set(Calendar.YEAR, cal1.get(Calendar.YEAR));
cal2.set(Calendar.MONTH, cal1.get(Calendar.MONTH));
cal2.set(Calendar.DATE, cal1.get(Calendar.DATE));
cal2.set(Calendar.HOUR_OF_DAY, cal1.get(Calendar.HOUR_OF_DAY));
//simile for whatever level of field precision is needed
Date shiftedDate = cal2.getTime();
答案 1 :(得分:1)
你走了:
/**
* Convert a calendar from its current time zone to UTC (Greenwich Mean Time)
* @param local the time
* @return a calendar with the UTC time
*/
public static Calendar convertTimeToUtc(Calendar local){
int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
GregorianCalendar utc = new GregorianCalendar(TZ_UTC);
utc.setTimeInMillis(local.getTimeInMillis());
utc.add(Calendar.MILLISECOND, -offset);
return utc;
}
/**
* Convert a UTC date into the specified time zone
* @param tzName the name of the time zone for the output calendar
* @param utc the UTC time being converted
* @return a calendar in the specified time zone with the appropriate date
*/
public static Calendar convertTimeToLocal(String tzName, Calendar utc) {
TimeZone zone = TimeZone.getTimeZone(tzName);
int offset = zone.getOffset(utc.getTimeInMillis());
GregorianCalendar local = new GregorianCalendar(zone);
local.setTimeInMillis(utc.getTimeInMillis());
local.add(Calendar.MILLISECOND, offset);
return local;
}
/**
* Convert a UTC date into the specified time zone
* @param zone the time zone of the output calendar
* @param utc the UTC time being converted
* @return a calendar in the specified time zone with the appropriate date
*/
public static Calendar convertTimeToLocal(TimeZone zone, Calendar utc) {
int offset = zone.getOffset(utc.getTimeInMillis());
GregorianCalendar local = new GregorianCalendar(zone);
local.setTimeInMillis(utc.getTimeInMillis());
local.add(Calendar.MILLISECOND, offset);
return local;
}
答案 2 :(得分:0)
如果您不使用日历,您使用的是什么?也许另一个图书馆
如果没有,你的时区末尾就有那个+3 ......你可以用它来碰撞小时(+/-)X;在这种情况下,+ 3。请记住,在这种情况下(例如)11 + 3 = 2。这个数学可以通过添加小时+偏移量,取该值%12,并将该答案设置为小时(如果需要,将答案设置为0到12)来完成。这有意义吗?
答案 3 :(得分:0)
我找到了一种使用所需时区的rowOffset来实现这一目标的简单方法:
Date date = new Date();
int rawOffset = TimeZone.getTimeZone("EST").getRawOffset();
Date adjustedDate = new Date(date.getTime() + rawOffset)
编辑:正如Affe指出的那样,这将忽略闰秒和夏令时。