我正在尝试创建一个易于访问的TimeDate变量,但我遇到了转换问题.在time.h中,如何将time_t(自1970年1月1日以来的秒数)转换为当前本地时区(如果适用则补偿夏令时),以便:
time_t Seconds;
Run Code Online (Sandbox Code Playgroud)
变为:
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
};
Run Code Online (Sandbox Code Playgroud)
在此过程中不使用任何字符串文字(时区名称栏)(以保持其效率)?这也考虑到了闰年.如果TimeDate可以转换回time_t,则可以获得奖励.
C标准库(可通过使用C++访问ctime)提供localtime了完全相同的目的(或gmtime用于UTC).struct tm如果有一些原因导致标准的不足以满足您的需求,那么您可以将结果用鞋头敲打到您自己的结构中.
有一件事它不提供是时区本身,但你可以得到(在ISO 8601格式的偏移量)通过使用strftime与%Z和%z格式字符串
举例来说,这是一个演示此操作的程序:
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我在我的盒子上运行时,我看到:
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
Run Code Online (Sandbox Code Playgroud)