2011-09-28 71 views
2

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

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 
}; 

在进程中不使用任何字符串文本(bar用于时区名称)(以保持其有效性)?这也考虑到了闰年。如果TimeDate可以转换回time_t,则为奖励。

回答

9

C标准库(通过使用ctime在C++中可访问的),用于精确地为此目的(或gmtime对于UTC)提供localtime。在此之后,如果标准人员不能满足您的需求,那么您可以将生成的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; 
} 

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

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 
+0

嗨,pax,看当地时间,它将放入tm结构,其中是天/小时/分钟...自1970年1月1日以来。这个问题是我不想自1970年1月1日以来经过了多少小时,我想要的是现在的时间(UTC格式,DST /时区分开)。它也不提供所用的时区或时区抵消的小时数。 – SSight3

+0

@ SSight3:我想你想再次阅读该说明。 – Nemo

+0

嗨,nemo,他修改了描述,因为我的评论,但它仍然没有解决我的问题,这是如何将time_t转换为TimeDate结构,IE如何转换成TimeDate是臭名昭着的丢失(释义:我该如何转换tm到TimeDate)。另请注意时区/闰年问题。 – SSight3