2

stringと に簡単に変換できるように、関数を作成しようとしてtime_ttime_tますstring。ただし、常に間違った年と間違った時間を教えてくれます。どうしたの?

OSに依存しない必要があります!

たとえば、日付30/11/2012:09:49:5530/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;
}
4

1 に答える 1

2

1900年以降の構造を保持しtm_yearます。std::tm

when.tm_year = yy;したがって、年から 1900 を減算する代わりに、次のようにします。when.tm_year = yy-1900;

ここで実行中のコードを確認できます。

編集:sfjacが指摘したように、私の答えはDSTの問題に対処していませんでした。

時間に関する問題は、DST フラグです。ideone では問題を再現できないため、ローカルでのみ..システムがローカル設定tm_isdstに基づいて設定されている可能性があります。

必要にwhen.tm_isdst応じて、 を 0 または負に設定する必要があります。日時に DST がないことがわかっている場合は 0 に設定し、不明な場合は -1 (負) に設定します。

于 2015-09-24T15:00:11.070 に答える