1.在標准C/C++中,我們可通過tm結構來獲得日期和時間,tm結構在time.h中的定義如下:
#ifndef _TM_DEFINED
struct tm {
int tm_sec; /* 秒–取值區間為[0,59] */
int tm_min; /* 分 - 取值區間為[0,59] */
int tm_hour; /* 時 - 取值區間為[0,23] */
int tm_mday; /* 一個月中的日期 - 取值區間為[1,31] */
int tm_mon; /* 月份(從一月開始,0代表一月) - 取值區間為[0,11] */
int tm_year; /* 年份,其值從1900開始 */
int tm_wday; /* 星期–取值區間為[0,6],其中0代表星期天,1代表星期一,以此類推 */
typedef __int64 __time64_t; /* 64-bit time value */
typedef __time64_t time_t; /* time value */
/* time_t 是一種時間類型,一般用來存放格林威治時間1970年01月01日00時00分00秒(北京時間1970年01月01日08時00分00秒)起至現在的總秒數 */
#include <stdio.h>
#include <time.h>
int GetNDaysGapDate(int iNowDate, int iNum)
{
struct tm ptm;
ptm.tm_year = iNowDate / 10000 % 10000 - 1900;
ptm.tm_mon = iNowDate / 100 % 100 - 1;
ptm.tm_mday = iNowDate % 100;
ptm.tm_hour = 0;
ptm.tm_min = 0;
ptm.tm_sec = 0;
time_t timep;
timep = mktime(&ptm); //mktime把struct tm類型轉換成time_t
timep += iNum * 24 * 60 * 60;
ptm = *localtime(&timep); //localtime把time_t類型轉換成struct tm
return (ptm.tm_year + 1900) * 10000 + (ptm.tm_mon + 1) * 100 + ptm.tm_mday;
}
int main()
{
int iDate = 20170120;
int n = 30;
int iPre30Date = GetNDaysGapDate(iDate, (-1)*n); //獲取 iDate 30天前的日期
return 0;
}
//距9:30的分鍾數可以表示成:
min = ptm.tm_hour*60 + ptm.tm_min - (9*60 + 30);
// long 型可直接賦值給 time_t 對象
long lTime = 1513318455;
time_t timestamp = 1513318455;
struct tm ptm;
ptm = *localtime(×tamp);
//獲取當前時間戳
time_t timep;
time(&timep);
cout << timep << endl;
//數據庫讀取的 update_time(YYYY-mm-dd HH:MM::SS)格式轉換成 struct tm
void strTimestampToStTm(const string strTimestamp, struct tm &stTm)
{
memset(&stTm, 0, sizeof(stTm));
sscanf(strTimestamp.c_str(), "%d-%d-%d %d:%d:%d", &stTm.tm_year, &stTm.tm_mon, &stTm.tm_mday, &stTm.tm_hour, &stTm.tm_min, &stTm.tm_sec);
stTm.tm_year -= 1900;
stTm.tm_mon--;
}
參見:https://blog.csdn.net/jiaolongdy/article/details/38372271
