time(NULL) 得到的标准计时点(一般是1970年1月1日午夜 注意时区,如东八区开始的时间是1970年1月1日 8:00:00 )到当前时间的秒数。
得到当天的00:00##
time_t ToDate(time_t nTime)
{
tm tmTime;
if (!localtime_r(&nTime, &tmTime))
return -1;
tmTime.tm_hour = 0;
tmTime.tm_min = 0;
tmTime.tm_sec = 0;
return mktime(&tmTime);
}
time_t
和std::wstring
互转
#define MAX_TIME_BUFFER_SIZE (128)
std::wstring FormatTime(time_t nTime)
{
tm* pTm = localtime(&nTime);
wchar_t wszBuffer[MAX_TIME_BUFFER_SIZE];
if (pTm == NULL || !wcsftime(wszBuffer, _countof(wszBuffer), L"%Y/%m/%d %H:%M:%S", pTm))
{
wszBuffer[0] = L'\0';
}
return wszBuffer;
}
time_t ParseTime(const std::wstring& wstrTime)
{
time_t nResult = 0;
time_t nTime = 0;
int nRetCode = false;
int nYear = 0;
int nMonth = 0;
int nDay = 0;
int nHour = 0;
int nMin = 0;
int nSec = 0;
tm Tm;
nRetCode = swscanf(wstrTime.c_str(), L"%d/%d/%d %d:%d:%d", &nYear, &nMonth, &nDay, &nHour, &nMin, &nSec);
FAILED_JUMP(nRetCode == 6);
FAILED_JUMP(nYear >= 1900);
FAILED_JUMP(nMonth >= 1 && nMonth <= 12);
FAILED_JUMP(nDay >= 1 && nDay <= 31);
FAILED_JUMP(nHour >= 0 && nHour <= 23);
FAILED_JUMP(nMin >= 0 && nMin <= 59);
FAILED_JUMP(nSec >= 0 && nSec <= 59);
Tm.tm_sec = nSec;
Tm.tm_min = nMin;
Tm.tm_hour = nHour;
Tm.tm_mday = nDay;
Tm.tm_mon = nMonth - 1; // tm_mon is 0 based
Tm.tm_year = nYear - 1900; // tm_year is 1900 based
Tm.tm_isdst = -1;
nTime = mktime(&Tm);
FAILED_JUMP(nTime != -1);
nResult = nTime;
Exit0:
return nResult;
}
lua中得到天数的做法
-- 获取时差(秒数)
-- 该函数是一个修订版,原来的做法
-- local tbTime = os.date("*t", 0);
-- return (tbTime.hour * 3600 + tbTime.min * 60 + tbTime.sec);
-- 在mac下是不对的
function GetGMTSec()
if not _nGMTSec then
local nTime = os.time();
local tbUtcDate = os.date("!*t", nTime);
local nUtcTime = os.time(tbUtcDate);
_nGMTSec = os.difftime(nTime, nUtcTime);
end
return _nGMTSec;
end
-- 根据秒数(UTC,GetTime()返回)计算当地天数
-- 1970年1月1日 返回0
-- 1970年1月2日 返回1
-- 1970年1月3日 返回2
-- ……依此类推
function GetLocalDay(nUtcSec)
local nLocalSec = (nUtcSec or os.time()) + GetGMTSec();
return math.floor(nLocalSec / (3600 * 24));
end
-- 注意:如果在东八区使用GetLocalDay(N) * (3600 * 24)得到的是早上八点,需要减去GetGMTSec()