staticinlineint64_tfloordiv(int64_t a,int b){return(a -(a <0? b -1:0))/ b;}staticinlineintfloordiv(int a,int b){return(a -(a <0? b -1:0))/ b;}// 当前的日期对应的儒略日staticinlineint64_tjulianDayFromDate(int year,int month,int day){// Adjust for no year 0if(year <0){++year;}/*
* Math from The Calendar FAQ at http://www.tondering.dk/claus/cal/julperiod.php
* This formula is correct for all julian days, when using mathematical integer
* division (round to negative infinity), not c++11 integer division (round to zero)
*/int a =floordiv(14- month,12);int64_t y =(int64_t)year +4800- a;int m = month +12* a -3;return day +floordiv(153* m +2,5)+365* y +floordiv(y,4)-floordiv(y,100)+floordiv(y,400)-32045;}
注:Qt使用qint64,C++使用int64_t
获取当前的日期和时间
enum{
SECS_PER_DAY =86400,// 一天的秒数
MSECS_PER_DAY =86400000,// 一天的毫秒数
SECS_PER_HOUR =3600,// 一小时的秒数
MSECS_PER_HOUR =3600000,// 一小时的毫秒数
SECS_PER_MIN =60,// 一分钟的秒数
MSECS_PER_MIN =60000,// 一分钟的毫秒数
TIME_T_MAX =2145916799,// int maximum 2037-12-31T23:59:59 UTC
JULIAN_DAY_FOR_EPOCH =2440588// result of julianDayFromDate(1970, 1, 1)};// 当前的时间对应的毫秒数staticinlineunsignedintmsecsFromDecomposed(int hour,int minute,int sec,int msec =0){return MSECS_PER_HOUR * hour + MSECS_PER_MIN * minute +1000* sec + msec;}
Q_OS_WIN:
#include<Windows.h>// 获取日期、时间
SYSTEMTIME st;memset(&st,0,sizeof(SYSTEMTIME));GetLocalTime(&st);typedefstruct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;} SYSTEMTIME,*PSYSTEMTIME,*LPSYSTEMTIME;
GetLocalTime:获取本地时间
GetSystemTime:获取通用协调时(UTC, Universal Time Coordinated)// 当前UTC时间距离1970.1.1过去的毫秒数int64_tcurrentMSecsSinceEpoch(){
SYSTEMTIME st;memset(&st,0,sizeof(SYSTEMTIME));GetSystemTime(&st);returnmsecsFromDecomposed(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds)+int64_t(julianDayFromDate(st.wYear, st.wMonth, st.wDay)-julianDayFromDate(1970,1,1))*int64_t(86400000);}// 当前UTC时间距离1970.1.1过去的秒数int64_tcurrentSecsSinceEpoch(){
SYSTEMTIME st;memset(&st,0,sizeof(SYSTEMTIME));GetSystemTime(&st);return st.wHour * SECS_PER_HOUR + st.wMinute * SECS_PER_MIN + st.wSecond +int64_t(julianDayFromDate(st.wYear, st.wMonth, st.wDay)-julianDayFromDate(1970,1,1))*int64_t(86400);}
Q_OS_UNIX:
// 当前UTC时间距离1970.1.1过去的毫秒数int64_tcurrentMSecsSinceEpoch(){// posix compliant system// we have millisecondsstruct timeval tv;gettimeofday(&tv,0);returnint64_t(tv.tv_sec)*int64_t(1000)+ tv.tv_usec /1000;}// 当前UTC时间距离1970.1.1过去的秒数int64_tcurrentSecsSinceEpoch(){struct timeval tv;gettimeofday(&tv,0);returnint64_t(tv.tv_sec);}struct timeval {
_kernel_time_t tv_sec;/* seconds */
_kernel_suseconds_t tv_usec;/* microseconds */};