c++日付と時間に関する操作-<br>(ctime)

2007 ワード

time.h(ctime)は、c time libraryであり、取得および操作日時の関数を定義する.
1.構造
typedef long time_t;
time_tはロング整数型で、(1970年、1月1日08:00:00)からの秒数を表し、しばしば
time関数を取得します.
struct tm {
int tm_sec; //  0-59(  )
int tm_min; //  0-59
int tm_hour; //  0-23
int tm_mday;//day 1-31
int tm_mon; // 0-11
int tm_year; //   1900      2013-1900 = 113
int tm_wday; //   0-6
int tm_yday; // 1 1   ,0-365
int tm_isdst;
tmは、カレンダーの日付および時間の各構成要素を含む
2.関数
time_t time ( time_t * timer );//      
time_t mktime ( struct tm * timeptr );// struct tm   time_t
struct tm * localtime ( const time_t * timer ); // time_t   struct tm
size_t strftime ( char * ptr, size_t maxsize, const char * format,
                  const struct tm * timeptr ); // struct tm             
char *strptime(const char *buf,const char *format,struct tm *timeptr); // format           struct tm
  
3.常用
#include <time.h>
time_t now;
now = time(NULL);//      

struct tm *timeinfo;
timeinfo = localtime(&now);//   tm

time_t seconds;
seconds = mktime(timeinfo);//   time_t
  time_t now = time(NULL);
  struct tm timeinfo = *localtime(&now);
  char buf[40];
  strftime(buf, sizeof(buf), "%Y%m%d%H%M%S", &timeinfo);
  cout << buf << endl;//20130207142133


  strptime("20130207112305", "%Y%m%d%H%M%S", &timeinfo);
  cout << timeinfo.tm_sec << endl;//5

4.現在時刻のms値の取得
#include <time.h>
#include <sys/time.h>
struct timeval tv;
gettimeofday (&tv, NULL);
uint64_t mseconds=tv.tv_sec * 1000 + tv.tv_usec / 1000;

timevalは時間値を指定するために使用され、構造は以下の通りです.
timeval{
time_t tv_sec; //  [long int]
suseconds_t tv_usec; //   [long int]
};

1つのメソッドの応答時間を計算するのによく使用されます.