我正在使用 Visual Studio c++ Compiler (2010),但该库具有不同的 ANSI C 和 POSIX 库函数实现。
ANSI C 函数和 Windows CRT 实现有什么区别?例如 tzset()
和 _tzset()
或 setenv()
和 _setenv()
有什么区别?似乎以同样的方式做同样的事情......
我正在使用 msvc ( 2010 ),我是否更喜欢 Windows CRT 实现?
编辑 1
嗯,我想以一种可移植的方式在 time_t
中转换以 UTC 表示的 struct tm,但是没有可移植的方法来做到这一点。我必须为不同的平台(Android、Linux、Windows、Windows CE)编写函数。
我见过 this stackoverflow post使用 setenv
、getenv
和 tzset
编辑2
不幸的是,经过一些测试,我发现 getenv("TZ")
在 Windows 上返回一个空指针。但是为什么将 UTC 时间结构转换为 time_t
如此困难?
编辑 3
从 Boost 我在 boost/chrono/io/time_point_io.hpp 中发现了这段代码。希望这对我有帮助。
inline int32_t is_leap(int32_t year)
{
if(year % 400 == 0)
return 1;
if(year % 100 == 0)
return 0;
if(year % 4 == 0)
return 1;
return 0;
}
inline int32_t days_from_0(int32_t year)
{
year--;
return 365 * year + (year / 400) - (year/100) + (year / 4);
}
inline int32_t days_from_1970(int32_t year)
{
static const int days_from_0_to_1970 = days_from_0(1970);
return days_from_0(year) - days_from_0_to_1970;
}
inline int32_t days_from_1jan(int32_t year,int32_t month,int32_t day)
{
static const int32_t days[2][12] =
{
{ 0,31,59,90,120,151,181,212,243,273,304,334},
{ 0,31,60,91,121,152,182,213,244,274,305,335}
};
return days[is_leap(year)][month-1] + day - 1;
}
inline time_t internal_timegm(std::tm const *t)
{
int year = t->tm_year + 1900;
int month = t->tm_mon;
if(month > 11)
{
year += month/12;
month %= 12;
}
else if(month < 0)
{
int years_diff = (-month + 11)/12;
year -= years_diff;
month+=12 * years_diff;
}
month++;
int day = t->tm_mday;
int day_of_year = days_from_1jan(year,month,day);
int days_since_epoch = days_from_1970(year) + day_of_year;
time_t seconds_in_day = 3600 * 24;
time_t result = seconds_in_day * days_since_epoch + 3600 * t->tm_hour + 60 * t->tm_min + t->tm_sec;
return result;
}
最佳答案
关于c++ - timegm 跨平台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16647819/