现在的位置: 首页 > 综合 > 正文

不同时间类型之间的转换之SYSTEMTIME 与 time_t

2016年06月27日 ⁄ 综合 ⁄ 共 834字 ⁄ 字号 评论关闭

SYSTEMTIME 与 time_t

time_t ConvertSYSTEMTIME2Timet(const SYSTEMTIME& st, BOOL bUseUTCTime)
{
	time_t ret = -1;
	struct tm gm = {st.wSecond, st.wMinute, st.wHour, st.wDay, st.wMonth-1, st.wYear-1900, st.wDayOfWeek, 0, 0};

	if (!bUseUTCTime)
		ret = mktime(&gm); // 反向转换 localtime, 使用本地时间
	else
		ret = _mkgmtime(&gm); // 反向转换 gmtime, 使用 UTC 时间
	return ret;
}

SYSTEMTIME ConvertTimet2SYSTEMTIME(time_t& t, BOOL bUseUTCTime)
{
	SYSTEMTIME st = { 1970, 1, 4, 1,0,0,0, 0 };
	tm* temptmPtr = NULL;
	//
	if (!bUseUTCTime)
	{
		SYSTEMTIME stTmp = st;
		SystemTimeToTzSpecificLocalTime(NULL, &st, &stTmp);
		st = stTmp;
		temptmPtr = localtime(&t); // 反向转换 mktime, 使用本地时间
	}
	else
		temptmPtr = gmtime(&t); // 反向转换 _mkgmtime, 使用 UTC 时间

	if (temptmPtr)
	{
		st.wYear = 1900 + temptmPtr->tm_year;
		st.wMonth = temptmPtr->tm_mon + 1;
		st.wDayOfWeek = temptmPtr->tm_wday;
		st.wDay = temptmPtr->tm_mday;
		st.wHour = temptmPtr->tm_hour;
		st.wMinute = temptmPtr->tm_min;
		st.wSecond = temptmPtr->tm_sec;
	}

	return st;
}

抱歉!评论已关闭.