time_t转换格式问题

time_t conversion format question

本文关键字:格式 问题 转换 time      更新时间:2023-10-16

我正在尝试制作一个易于访问的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,则奖金。

C 标准库(使用 ctime 在 C++ 中访问(提供了用于该目的的localtime(或 UTC gmtime(。如果标准结构不足以满足您的需求,您可以将生成的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