簡體   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