我正在尝试创建一个易于访问的TimeDate变量,但是我遇到了转换问题。在time.h中,如何将time_t(自1970年1月1日以来的秒数)转换为当前本地时区(如果适用则补偿夏令时),以便:
time_t Seconds;
变为:
struct TimeDate
{
short YYYY;
unsigned char MM;
unsigned char DD;
unsigned char HH; //Non-DST, non-timezone, IE UTC (user has to add DST and TZO to get what they need)
unsigned char MM;
unsigned char S;
char TZ[4]; //This can be optionally a larger array, null terminated preferably
char TZO; //Timezone Offset from UTC
char DST; //Positive is DST (and amount of DST to apply), 0 is none, negative is unknown/error
};
在此过程中不使用任何字符串文字(时区名称栏)(以保持其效率)?这也考虑到了闰年。奖金,如果TimeDate可以转换回time_t。
答案 0 :(得分:9)
C标准库(使用ctime
在C ++中可访问)提供localtime
用于此目的(或gmtime
用于UTC)。如果有一些原因导致标准版本不足以满足您的需求,那么您可以将结果struct tm
敲入您自己的结构中。
它没有提供的一件事是时区本身,但你可以使用strftime
和%Z
格式的%z
来获得(以及ISO 8601格式的偏移量)字符串
举例来说,这是一个演示此动作的程序:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main(void) {
time_t t;
struct tm *tim;
char tz[32];
char ofs[32];
std::system ("date");
std::cout << std::endl;
t = std::time (0);
tim = std::localtime (&t);
std::strftime (tz, sizeof (tz), "%Z", tim);
std::strftime (ofs, sizeof (ofs), "%z", tim);
std::cout << "Year: " << (tim->tm_year + 1900) << std::endl;
std::cout << "Month: " << (tim->tm_mon + 1) << std::endl;
std::cout << "Day: " << tim->tm_mday << std::endl;
std::cout << "Hour: " << tim->tm_hour << std::endl;
std::cout << "Minute: " << tim->tm_min << std::endl;
std::cout << "Second: " << tim->tm_sec << std::endl;
std::cout << "Day of week: " << tim->tm_wday << std::endl;
std::cout << "Day of year: " << tim->tm_yday << std::endl;
std::cout << "DST?: " << tim->tm_isdst << std::endl;
std::cout << "Timezone: " << tz << std::endl;
std::cout << "Offset: " << ofs << std::endl;
return 0;
}
当我在盒子上运行时,我看到了:
Wed Sep 28 20:45:39 WST 2011
Year: 2011
Month: 9
Day: 28
Hour: 20
Minute: 45
Second: 39
Day of week: 3
Day of year: 270
DST?: 0
Timezone: WST
Offset: +0800