繁体   English   中英

将time_t转换为字符串,将字符串转换为time_t会给出错误的年份和一个小时

[英]Convert time_t to string and string to time_t gives wrong year and an hour

我正在尝试编写函数来帮助自己轻松地将string转换为time_t并将time_t转换为string 但是,它总是给我错误的一年零一个小时。 怎么了?

我需要它独立于操作系统!

例如,对于日期30/11/2012:09:49:55它给出的是30/11/3912:08:49:55而不是30/11/2012:09:49:55

#include <iostream>
#include <string.h>
#include <cstdio>
using namespace std;

time_t string_to_time_t(string s)
{
    int yy, mm, dd, hour, min, sec;
    struct tm when;
    long tme;

    memset(&when, 0, sizeof(struct tm));
    sscanf(s.c_str(), "%d/%d/%d:%d:%d:%d", &dd, &mm, &yy, &hour, &min, &sec);

    time(&tme);
    when = *localtime(&tme);
    when.tm_year = yy;
    when.tm_mon = mm-1;
    when.tm_mday = dd;
    when.tm_hour = hour;
    when.tm_min = min;
    when.tm_sec = sec;

    return mktime(&when);
}

string time_t_to_string(time_t t)
{
    char buff[20];
    strftime(buff, 20, "%d/%m/%Y:%H:%M:%S", localtime(&t));
    string s(buff);
    return s;
}

int main()
{
    string s = "30/11/2012:13:49:55";

    time_t t = string_to_time_t(s);
    string ss = time_t_to_string(t);

    cout << ss << "\n";


    return 0;
}

std::tm结构中的tm_year保留自1900年以来的年份。

因此,而不是when.tm_year = yy; 必须从年份中减去1900: when.tm_year = yy-1900;

您可以在此处检查运行的代码。

编辑:正如sfjac指出的那样,我的答案没有解决DST问题。

小时的问题是DST标志。 由于我无法在ideone上重现该问题,因此只能在本地进行。系统可能tm_isdst根据本地设置来设置tm_isdst

您将需要根据需要将when.tm_isdst设置为0或负数。 如果您知道日期时间没有DST,则设置为0;如果未知,则设置为-1(负)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM