LoginSignup
18
20

More than 5 years have passed since last update.

【c++】明日、昨日、指定した日付を取得する

Last updated at Posted at 2016-01-25

元ブログ - 【c++】明日、昨日、指定した日付を取得する - 技術は熱いうちに打て!

c++で明日とか昨日とか指定した日付とか取得する方法が分かりそうで分からなかったので簡単に書きたいと思います。

現在時刻の取得

time_t now = std::time(nullptr);

まず、一番基本形です。
time関数にnullptrを渡すと、1970年1月1日からの経過秒がtime_t型変数で返ってきます。
ちなみにtime_tは、longのエイリアスです。

指定日付の取得

// yearh since 1900なので1900をマイナス
// tak0kadaさん、ありがとうございます
struct tm birthdayStruct = { 0, 23, 13, 3, 10, 1987 - 1900 };
time_t birthday = std::mktime(&birthdayStruct);

さて、1行目にtm構造体が出て来ました。
これは暦時刻の要素を格納する構造体です。

time.h
struct tm {
    int  tm_sec;    /* seconds after the minute [0-60] */
    int  tm_min;    /* minutes after the hour [0-59] */
    int  tm_hour;   /* hours since midnight [0-23] */
    int  tm_mday;   /* day of the month [1-31] */
    int  tm_mon;    /* months since January [0-11] */
    int  tm_year;   /* years since 1900 */
    int  tm_wday;   /* days since Sunday [0-6] */
    int  tm_yday;   /* days since January 1 [0-365] */
    int  tm_isdst;  /* Daylight Savings Time flag */
    long tm_gmtoff; /* offset from CUT in seconds */
    char *tm_zone;  /* timezone abbreviation */
};

この構造体にアクセスすることで、具体的な年月日などを取得出来ます。
ここでは時間指定をしてtm構造体を作成しています。


{ 秒, 分, 時, 日, 月, 年 }

の順で指定しています。
ここでは、1987年10月3日 13時23分0秒を表すtm構造体が返ってきます。
最後に、この構造体のポインタをstd::mktime関数に渡してやることでtime_t型で返ってきます。

明日/昨日の取得

※ここで言う明日/昨日とは0時ジャストを考えてください。

time_t now = std::time(nullptr);
struct tm* localNow = std::localtime(&now);

struct tm tomorrowStruct = { 0, 0, 0, localNow->tm_mday + 1, localNow->tm_mon, localNow->tm_year };
time_t tomorrow = std::mktime(&tomorrowStruct);

2行めのlocaltimeはtime_t型ポインタを渡すと、現地時間のtm構造体のポインタを返してくれる関数です。

先ほどのtm構造体の作り方で明日の0時0分0秒を作成したいのでday + 1としています。
昨日であれば、day - 1としてやれば出来ます。
簡単ですね。

誰かのお役に立てば。

18
20
4

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
18
20