C/C++ 时间戳和标准日期相互转换
写法不限,仅供参考!
/**
-
时间戳转成普通日期格式
-
计算方式如下:
-
第一种:1970/01/01 00:00:00
-
第二种:1970/01/01 08:00:00
*/
int FuncTimeStamp2RegularDate(const unsigned long long ullData, const bool bAdd8Hours, int *pnYear,
int *pnMonth, int *pnDay, int *pnHour, int *pnMin, int *pnSec)
{
int nBasicYears = 1970; // 从1970年开始算起
int nOneMinSecs = 60; // 一分钟60秒
int nOneHourSecs = 3600; // 一小时3600秒
long nOneDaySecs = 86400; // 一天86400秒
bool bLeapYear = false;
unsigned long long nSecSum = 0;
int nMonthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (true==bAdd8Hours)
nSecSum = ullData + (8*nOneHourSecs);
else
nSecSum = ullData;
long nDaysCalc = nSecSum / nOneDaySecs;
long nOtherSecs = nSecSum % nOneDaySecs;
for ( ; nDaysCalc>=365; )
{
bLeapYear = FuncChkLeapYear(nBasicYears);
if (true==bLeapYear)
nDaysCalc -= 366;
else
nDaysCalc -= 365;
nBasicYears += 1;
}
bLeapYear = FuncChkLeapYear(nBasicYears);
*pnYear = nBasicYears;
int nIndex = 0;
for ( ; (nIndex<12)&&(nDaysCalc>=nMonthDays[nIndex+1]); nIndex++)
{
if (nIndex==1)
{
if (true==bLeapYear)
nDaysCalc -= 29;
else
nDaysCalc -= nMonthDays[nIndex];
}
else
nDaysCalc -= nMonthDays[nIndex];
}
*pnMonth = nIndex + 1;
*pnDay = nDaysCalc + 1;
*pnHour = (nOtherSecs/nOneHourSecs);
*pnMin = ((nOtherSecs%nOneHourSecs)/nOneMinSecs);
*pnSec = (nOtherSecs%nOneMinSecs);
return APP_SUCC;
}
bool FuncChkLeapYear(const int nYear)
{
if ((nYear%4==0 && nYear%100!=0) || (nYear%400==0))
{
return true;
}
else
{
return false;
}
}
ull 转换日期到时间戳 标志位bCalc8Hour用于控制时区转换 年份nYear和月份nMonth
const int nDay, const int nHour, const int nMin, const int nSec)
{
int nMinSecs = 60;
int nHourSecs = 3600;
long lOneDaySecs = 86400;
unsigned long long ullStampTime = 0;
bool bLeapYear = false;
for (int nYearTemp=1970; nYearTemp<nYear; nYearTemp++)
{
bLeapYear = FuncChkLeapYear(nYearTemp);
if (true==bLeapYear)
ullStampTime += 366 * lOneDaySecs;
else
ullStampTime += 365 * lOneDaySecs;
}
int nIndex = 1;
for (; nIndex<nMonth; nIndex++)
{
if (nIndex==1 ||nIndex==3 ||nIndex==5 ||nIndex==7 ||nIndex==8 ||nIndex==10 ||nIndex==12)
{
ullStampTime += 31 * lOneDaySecs;
}
else if (nIndex==4 ||nIndex==6 ||nIndex==8 ||nIndex==9 ||nIndex==11)
{
ullStampTime += 30 * lOneDaySecs;
}
else
{
if (true==FuncChkLeapYear(nYear))
ullStampTime += 29 * lOneDaySecs;
else
ullStampTime += 28 * lOneDaySecs;
}
}
ullStampTime += (nDay-1) * lOneDaySecs;
ullStampTime += nHour * nHourSecs;
ullStampTime += nMin * nMinSecs;
ullStampTime += nSec;
if (true==bCalc8Hour)
return ullStampTime - (8*nHourSecs);
else
return ullStampTime;
}
