如何将java日期转换为基于时区的日期对象



所以我将时间戳保存为Date对象,将时区保存为TimeZone对象。

现在我想做一个函数,以Date对象和TimeZone对象作为参数,并返回使用时间戳调整的Date对象。

例如:

输入:

<>之前日期时区莫斯科标准时间12:00 (UTC+3)之前输出:

<>之前日期3:00之前编辑:

删除关于Calendar

的说明

java.util.Date是绝对时间点。0900小时UTC1200小时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();

给你:

/**
 * 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;
}

如果你不使用日历,你在使用什么?也许是另一家图书馆?

如果没有,你在你的时区末尾有一个+3…你可以用它来调小时(+/-)X;这里是+3。只要记住,在这种情况下(例如)11+3=2。这个运算可以通过将hour + offset相加,取该值% 12,并将答案设置为小时(如果需要,将答案设置为0到12)来完成。明白了吗?

我找到了一种简单的方法来实现这一点,使用所需时区的rowOffset:

Date date = new Date();
int rawOffset = TimeZone.getTimeZone("EST").getRawOffset(); 
Date adjustedDate = new Date(date.getTime() + rawOffset)

编辑:正如Affe指出的那样,这将忽略闰秒和夏令时。

相关内容

  • 没有找到相关文章

最新更新