Skip to content

Instantly share code, notes, and snippets.

@pn11
Last active November 9, 2021 03:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pn11/91e7a0a2ede247a701d98b06b1a0b703 to your computer and use it in GitHub Desktop.
Save pn11/91e7a0a2ede247a701d98b06b1a0b703 to your computer and use it in GitHub Desktop.
C++ で Unix time を扱う

C++ で Unix time を扱う

面倒なので unix time を扱うときは Ruby とかで書いていたのだけど、C++ で書かなければならなくなったので、改めてちゃんと調べた。ちゃんと調べても分かりにくい仕様だったので、めも。基本的には以下の2つを参照するのが良さそう。

サンプルコードを書いてみた。

#include <iostream>
#include <ctime>
using namespace std;

int main() {
	// your code goes here

    time_t previous_time = 1470104004; // input previous time by hand

    // convert time_t to structure tm. You can use instead gmtime() for UTC
    tm *tm_previous = localtime(&previous_time);

	// print time using asctime() function.
	cout << asctime(tm_previous);

	// for current time
    time_t current_time = time(0); // get current time
    tm *tm_current = localtime(&current_time);
	cout << asctime(tm_current);

	// print by accessing contents of the structure
    cout << tm_current->tm_year + 1900 // year 0 corresponds to 1900
    << "/" << tm_current->tm_mon+1 // month starts from 0
    << "/" << tm_current->tm_mday  // mday means day in a month
    << " " << tm_current->tm_hour 
    << ":" << tm_current->tm_min
    << ":" << tm_current->tm_sec <<endl;
    

	// get unixtime from YY-mm-dd

    tm *jan2014 = localtime(&current_time);
    jan2014->tm_year = 2014 - 1900;
    jan2014->tm_mon = 1 - 1;
    jan2014->tm_mday = 1;
    jan2014->tm_hour = 0;
    jan2014->tm_min = 0;
    jan2014->tm_sec = 0;
    
    // print unix time
    cout << mktime(jan2014) << endl;
    
    // print datime
    cout << asctime(jan2014) << endl;

	return 0;
}

ideone で実行するとこんな感じ。

今実行すると出力はこんな感じ。

Tue Aug 2 02:13:24 2016
Tue Aug 2 03:55:19 2016
2016/8/2 3:55:19
1388534400
Wed Jan 1 00:00:00 2014

ideone のサーバーの local time は UTC と同じみたい。

Other References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment