C/C++ 时间相关用法
生活随笔
收集整理的這篇文章主要介紹了
C/C++ 时间相关用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基本時間函數:
1. 名字:time_t time(time_t *t)
? ? 說明:返回格林尼治時間從公元 1970 年1 月1 日的UTC 時間從0 時0 分0 秒算起到現在所經過的秒數,函數為value - result型
? ? 參數:time_t為長整型,即long型,所以最大能保存到2038年1月18日19時14分07秒
時間常用用法:
? ?1.1?獲取當前時間戳(精確到秒)
? ? 示例:
int nCurTime = time(NULL);? ??
? ? 1.2? 獲取從1970年1月1日算起至今經過的天數(從1開始,以北京時間的日期為天數標準,達到0時0分0秒即為新的一天)
? ? 示例:
// 一天的總秒數int DaySecond = 24 * 60 * 60;// 現在的時間戳,精確到秒int curTime = time(NULL);// 得到天數,為什么要減去16個小時呢,請參照上面圖片,北京的0時是格林尼治時間的16時// 所以只有減去了16小時的秒數,才是格林尼治時間的一天的0時0分0秒,當然此種計算只適用于以北京時間為標準的int curDay = (curTime - 16 * 60 * 60) / DaySecond;? ? 1.3?有了以前的時間戳(精確到秒),計算現在是時間戳計算以來的第幾天(從1開始,處于同一天則為1,以北京時間的日期為天數標準,達到0時0分0秒即為新的一天)
? ? 示例:
// 一天的總秒數int DaySecond = 24 * 60 * 60; // 上次的時間戳,暫取北京時間2017年3月1日0時0分0秒int nLastTime = 1488297600; // 上次時間戳所處的天數,減16小時秒數的原因同上int nLastDay = (nLastTime - 16* 60*60) / DaySecond ; // 當前時間戳所處的天數,減16小時秒數的原因同上int nCurDay = (time(NULL) - 16 * 60 * 60)/ DaySecond; // 間隔,加1表當天為第一天int nIntervalDay= nCurDay - nLastDay + 1;2. 時間結構體 tm 和?time_t的轉換
? ? 結構體tm的定義:
struct tm {int tm_sec; /* seconds after the minute - [0,59] */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 */ };? ? time_t的定義:即32位整型或64位整型
#ifndef _TIME_T_DEFINED #ifdef _USE_32BIT_TIME_T typedef __time32_t time_t; /* time value */ #else typedef __time64_t time_t; /* time value */ #endif? ? 2.1 tm轉換為time_t
time_t mktime(struct tm * _Tm);? ? 示例代碼:
tm* tm1 = new tm();tm1->tm_year = 118; // 2018年tm1->tm_mon = 3; // 4月tm1->tm_mday = 14; // 14日tm1->tm_hour = 10; // 10點tm1->tm_min = 58; // 58分tm1->tm_sec = 9; // 9秒time_t ti_t1 = mktime(tm1);cout<<"time_t1 value is "<<ti_t1<<endl;? ? 示例結果:
? ??
? ? 2.2 time_t轉換為tm
tm * localtime(const time_t * _Time);? ? 示例代碼:
// 獲取當前時間time_t ti = time(NULL);//轉換成tm類型的結構體;tm * time = localtime(&ti);cout<<"year="<<time->tm_year<<endl;cout<<"mon="<<time->tm_mon<<endl;cout<<"day="<<time->tm_mday<<endl;cout<<"hour="<<time->tm_hour<<endl;cout<<"min="<<time->tm_min<<endl;cout<<"sec="<<time->tm_sec<<endl;? ? 示例結果:
? ??
? ??
總結
以上是生活随笔為你收集整理的C/C++ 时间相关用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 万能makefile深入浅出- 第一篇
- 下一篇: 万能makefile深入浅出 - 第三篇