将日期和时间数字转换为 time_t 并指定时区

新手上路,请多包涵

我有以下整数:

 int y, mon, d, h, min, s;

Their values are: 2012 , 06 , 27 , 12 , 47 , 53 分别。如果我在我的应用程序的其他地方选择了“UTC”,我想表示“2012/06/27 12:47:53 UTC”的日期时间,或者如果我选择了“2012/06/27 12:47:53 AEST”的日期时间在我的应用程序的其他地方选择了“AEST”。

我想将其转换为 time_t ,这是我目前使用的代码:

 struct tm timeinfo;
timeinfo.tm_year = year - 1900;
timeinfo.tm_mon = mon - 1;
timeinfo.tm_mday = day;
timeinfo.tm_hour = hour;
timeinfo.tm_min = min;
timeinfo.tm_sec = sec;
//timeinfo.tm_isdst = 0; //TODO should this be set?

//TODO find POSIX or C standard way to do covert tm to time_t without in UTC instead of local time
#ifdef UNIX
return timegm(&timeinfo);
#else
return mktime(&timeinfo); //FIXME Still incorrect
#endif

所以我使用的是 tm structmktime ,但是这不是很好,因为它总是假设我的本地时区。

这样做的正确方法是什么?

所以下面是我到目前为止提出的解决方案。它基本上做三件事之一:

  1. 如果是 UNIX,只需使用 timegm
  2. 如果不是 UNIX
    1. 或者,使用 UTC 纪元和本地纪元之间的差异作为偏移量进行数学运算
      • 保留:数学可能不正确
    2. 或者,将“TZ”环境变量临时设置为 UTC
      • 保留:如果/当此代码需要多线程时会出错
namespace tmUtil
{
    int const tm_yearCorrection = -1900;
    int const tm_monthCorrection = -1;
    int const tm_isdst_dontKnow = -1;

#if !defined(DEBUG_DATETIME_TIMEGM_ENVVARTZ) && !(defined(UNIX) && !defined(DEBUG_DATETIME_TIMEGM))
    static bool isLeap(int year)
    {
        return
            (year % 4) ? false
            : (year % 100) ? true
            : (year % 400) ? false
            : true;
    }

    static int daysIn(int year)
    {
        return isLeap(year) ? 366 : 365;
    }
#endif
}

time_t utc(int year, int mon, int day, int hour, int min, int sec)
{
    struct tm time = {0};
    time.tm_year = year + tmUtil::tm_yearCorrection;
    time.tm_mon = mon + tmUtil::tm_monthCorrection;
    time.tm_mday = day;
    time.tm_hour = hour;
    time.tm_min = min;
    time.tm_sec = sec;
    time.tm_isdst = tmUtil::tm_isdst_dontKnow;

    #if defined(UNIX) && !defined(DEBUG_DATETIME_TIMEGM) //TODO remove && 00
        time_t result;
        result = timegm(&time);
        return result;
    #else
        #if !defined(DEBUG_DATETIME_TIMEGM_ENVVARTZ)
            //TODO check that math is correct
            time_t fromEpochUtc = mktime(&time);

            struct tm localData;
            struct tm utcData;
            struct tm* loc = localtime_r (&fromEpochUtc, &localData);
            struct tm* utc = gmtime_r (&fromEpochUtc, &utcData);
            int utcYear = utc->tm_year - tmUtil::tm_yearCorrection;
            int gmtOff =
                (loc-> tm_sec - utc-> tm_sec)
                + (loc-> tm_min - utc-> tm_min) * 60
                + (loc->tm_hour - utc->tm_hour) * 60 * 60
                + (loc->tm_yday - utc->tm_yday) * 60 * 60 * 24
                + (loc->tm_year - utc->tm_year) * 60 * 60 * 24 * tmUtil::daysIn(utcYear);

            #ifdef UNIX
                if (loc->tm_gmtoff != gmtOff)
                {
                    StringBuilder err("loc->tm_gmtoff=", StringBuilder((int)(loc->tm_gmtoff)), " but gmtOff=", StringBuilder(gmtOff));
                    THROWEXCEPTION(err);
                }
            #endif

            int resultInt = fromEpochUtc + gmtOff;
            time_t result;
            result = (time_t)resultInt;
            return result;
        #else
            //TODO Find a way to do this without manipulating environment variables
            time_t result;
            char *tz;
            tz = getenv("TZ");
            setenv("TZ", "", 1);
            tzset();
            result = mktime(&time);
            if (tz)
                setenv("TZ", tz, 1);
            else
                unsetenv("TZ");
            tzset();
            return result;
        #endif
    #endif
}

注意 StringBuilder 是一个内部类,对于这个问题来说没关系。

更多信息:

我知道这可以使用 boost 等轻松完成。但这不是选项。我需要它以数学方式完成,或者使用 ac 或 c++ 标准函数,或它们的组合。

timegm 似乎解决了这个问题,但是,它似乎不是 C / POSIX 标准的一部分。这段代码目前在多个平台(Linux、OSX、Windows、iOS、Android (NDK))上编译,所以我需要找到一种方法让它在所有这些平台上工作,即使解决方案涉及 #ifdef $PLATFORM 输入东西。

原文由 bguiz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 521
2 个回答

这让我有点想吐在嘴里,但是您可以使用 strftime() 将其转换为字符串,替换字符串中的时区,然后将其转换回 strptime() 并进入 time_tmktime() 。详细地:

 #ifdef UGLY_HACK_VOIDS_WARRANTY
time_t convert_time(const struct tm* tm)
{
    const size_t BUF_SIZE=256;
    char buffer[BUF_SIZE];
    strftime(buffer,256,"%F %H:%M:%S %z", tm);
    strncpy(&buffer[20], "+0001", 5); // +0001 is the time-zone offset from UTC in hours
    struct tm newtime = {0};
    strptime(buffer, "%F %H:%M:%S %z", &newtime);
    return mktime(&newtime);
}
#endif

但是,我强烈建议您说服权力毕竟增强是一种选择。 Boost 对自定义时区有很好的支持。还有其他库也可以优雅地做到这一点。

原文由 smocking 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您只想将 UTC 中给出的 struct tm 转换为 time_t 那么您可以这样做:

 #include <time.h>

time_t utc_to_time_t(struct tm* timeinfo)
{
    tzset(); // load timezone information (this can be called just once)

    time_t t = mktime(timeinfo);
    return t - timezone;
}

这基本上将 UTC 时间转换为 time_t 就好像给定时间是本地时间,然后对结果应用时区校正以将其恢复为 UTC。

在 gcc/cygwin 和 Visual Studio 2010 上测试。

我希望这有帮助!

更新:正如您很好指出的那样,当查询日期的夏令时状态与当前时间不同时,我上面的解决方案可能会返回一个小时的 time_t 值。

该问题的解决方案是有一个附加函数,它可以告诉您日期是否在 DST 区域内,并使用该函数和当前 DST 标志来调整 mktime 返回的时间。这实际上很容易做到。当您调用 mktime() 您只需将 tm_dst 成员设置为 -1,然后系统将尽力在给定时间为您计算 DST。假设我们对此信任系统,那么您可以使用此信息进行更正:

 #include <time.h>

time_t utc_to_time_t(struct tm* timeinfo)
{
    tzset(); // load timezone information (this can be called just once)

    timeinfo->tm_isdst = -1; // let the system figure this out for us
    time_t t = mktime(timeinfo) - timezone;

    if (daylight == 0 && timeinfo->tm_isdst != 0)
        t += 3600;
    else if (daylight != 0 && timeinfo->tm_isdst == 0)
        t -= 3600;
    return t;
}

原文由 Miguel Grinberg 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题