首页 > 解决方案 > 显示针对不同时区格式化的 ICU UDate

问题描述

在以下示例中,我想在不同时区格式化EPOCH (1/1/1970)。例如,我可能希望使用Los Angeles 时区格式化 EPOCH 和/或使用New York timezone格式化 EPOCH 。

UErrorCode uErrorCode = U_ZERO_ERROR;
UnicodeString unicodeString;
UDate uDate;

icu::Locale locale = icu::Locale("en");
TimeZone* timeZone = TimeZone::createTimeZone("America/Los_Angeles");
Calendar* calendar = Calendar::createInstance(timeZone, uErrorCode);

// setting calendar to EPOCH, e.g. zero MS from 1/1/1970
calendar->setTime(0, uErrorCode);

// get calendar time as milliseconds (UDate)
uDate = calendar->getTime(uErrorCode);

DateFormat* dateFormat = DateFormat::createDateTimeInstance(
    icu::DateFormat::MEDIUM,    // date style
    icu::DateFormat::SHORT,     // time style
    locale);

unicodeString = dateFormat->format(uDate, unicodeString, uErrorCode);

std::string str;
unicodeString.toUTF8String(str);
std::cout << "Date: " << str;

// Use getOffset to get the stdOffset and dstOffset for the given time
int32_t stdOffset, dstOffset;
timeZone->getOffset(uDate, true, stdOffset, dstOffset, uErrorCode);
std::cout << " | ";
std::cout << "Time zone STD offset: " << stdOffset / (1000 * 60 * 60) << " | ";
std::cout << "Time zone DST offset: " << dstOffset / (1000 * 60 * 60) << std::endl;

我遇到的问题是输出未针对时区进行格式化。

以下是使用洛杉矶时区时的输出:

日期:1969 年 12 月 31 日下午 6:00 | 时区 STD 偏移量:-8 | 时区 DST 偏移量:0

这是使用纽约时区时的输出:

日期:1969 年 12 月 31 日下午 6:00 | 时区 STD 偏移量:-5 | 时区 DST 偏移量:0

请注意日期不是 EPOCH,其次请注意两个输出的日期和时间是相同的。偏移量正确,但日期/时间显示不正确。

更新

重要的是要注意,显示的日期/时间比我目前(-6 UTC)晚了 6 小时,这意味着您将6 小时添加到1969 年 12 月 31 日下午 6 点,这将等于1 月 1 日的 EPOCH, 1970 年上午 12:00

ICU 正在自动使用我的 PC 的时区,因为我在使用DateFormat::Format(...)格式化日期/时间时找不到指定时区的方法。如果format()接受时区参数来覆盖我的 PC 的本地时区,我就不会遇到这个问题。

标签: icu

解决方案


您应该致电dateFormat->setTimeZone(*timeZone)指定时区。


推荐阅读