gpt4 book ai didi

c++ - time_t转换格式问题

转载 作者:太空狗 更新时间:2023-10-29 23:47:01 25 4
gpt4 key购买 nike

我正在尝试创建一个易于访问的 TimeDate 变量,但在转换时遇到了问题。在 time.h 中,我如何将 time_t(自 1/1/1970 以来的秒数)转换为当前本地时区(如果适用,补偿夏令时),以便:

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,则奖励。

最佳答案

C 标准库(可在 C++ 中使用 ctime 访问)正是为此目的提供了 localtime(或为 UTC 提供了 gmtime)。之后如果标准结构不能满足您的需求,您可以将生成的 struct tm 塞进您自己的结构中。

它没有提供的一件事是时区本身,但您可以通过使用 strftime%Z 来获得它(以及 ISO 8601 格式的偏移量)和 %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;
}

当我在我的盒子上运行它时,我看到:

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

关于c++ - time_t转换格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7582263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com