LoginSignup
0
0

More than 1 year has passed since last update.

[C++] yyyyMMdd形式の文字列を日付(tm)に直す

Last updated at Posted at 2020-11-25

もくじ

やりたいこと

別の記事で取り込んだyyyyMMdd形式の文字列を、tm構造体に入れて、日付として比較などできるようにしたい。

やり方

やり方は下記。

  • sscanf_s()で、20201012などのyyyyMMdd文字列の中の年/月/日の数字を、分解してint型の変数に入れる(今回はwchar_tの文字列なので、swscanf_s()を使う)
  • そいつらをtmに入れなおす
  • そのtmを、mktime()でtime_tに入れなおす→①
  • 比較対象のtime_tを用意する→②
  • ①と②のtime_tを、disstime()関数で比較する

これで、比較ができる。
下のサンプルでは、②として「今の時間」を使った。

サンプル

#include <windows.h>
#include <timezoneapi.h> 
#include <iostream>
#include <time.h>
#include <regex>

int main()
{
    int year, month, day = 0;
    std::wstring input = L"20201115";

    // 文字列をintとして取り込み
    swscanf_s(input.c_str(), L"%04d%02d%02d", &year, &month, &day);

    // tmに移し替え
    tm myTm = { 0 };
    myTm.tm_year = year - 1900;
    myTm.tm_mon = month - 1;
    myTm.tm_mday = day;

    // ログファイル名からログ日時を取得
    time_t log = mktime(&myTm);

    // 現在日時を取得
    auto t = std::time(nullptr);
    auto tmnow = tm();
    localtime_s(&tmnow, &t);

    // ログの時間と今の時間を比較
    double dif = difftime(t, log);

    // 経過した日数を算出(difftimeの戻り値は秒)
    int keikabi = dif / 60 / 60 / 24;

    std::wcout << L"Keika shita Hi ha : " << keikabi << std::endl;

    system("pause");
}

参考

[C言語] 時間を扱う
https://qiita.com/edo_m18/items/364ffc6713b81c4d1c87

sscanf_s
https://docs.microsoft.com/ja-jp/cpp/c-runtime-library/reference/sscanf-s-sscanf-s-l-swscanf-s-swscanf-s-l?view=msvc-160

mktime
https://docs.microsoft.com/ja-jp/cpp/c-runtime-library/reference/mktime-mktime32-mktime64?view=msvc-160

difftime
https://docs.microsoft.com/ja-jp/cpp/c-runtime-library/reference/difftime-difftime32-difftime64?view=msvc-160

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0