提供两个字符串与时间格式COleDateTime的转换

也是无意中看到别人的转换代码,这里贴出来,分享出来,已备用。

///< 字符串格式转换为COleDateTime格式:

BOOL ParseDateTimeISO8601(COleDateTime& rDT, LPCTSTR pcszDateTime)
{
	SYSTEMTIME st;
	ZeroMemory(&st, sizeof(SYSTEMTIME));

	int nResult = SCANF_S(pcszDateTime, _T("%hu-%hu-%huT%hu:%hu:%hu"),
		&st.wYear, &st.wDay, &st.wMonth, &st.wHour, &st.wMinute, &st.wSecond);

	if (nResult == 3 || nResult == 5 || nResult == 6)
	{
		COleDateTime dtTemp(st);
		if (dtTemp.GetStatus() != COleDateTime::valid)
			return FALSE;

		rDT = dtTemp;
		return TRUE;
	}

	ZeroMemory(&st, sizeof(SYSTEMTIME));

	nResult = SCANF_S(pcszDateTime, _T("%hu:%hu:%hu"),
		&st.wHour, &st.wMinute, &st.wSecond);

	if (nResult == 2 || nResult == 3)
	{
		double dblTime = (((long)st.wHour * 3600L) +  // hrs in seconds
			((long)st.wMinute * 60L) +  // mins in seconds
			((long)st.wSecond)) / 86400.;

		rDT = dblTime;
		return TRUE;
	}

	return FALSE;
}

///< COleDateTime 转 字符串

CString FormatDateTimeISO8601(const COleDateTime& dt)
{
	ASSERT(dt.m_status == COleDateTime::valid);

	CString strValue;

	if ((DWORD)dt == 0)
	{
		strValue = dt.Format(_T("%H:%M:%S"));
	}
	else if ((double)(DWORD)(dt) == (double)dt)
	{
		strValue = dt.Format(_T("%Y-%d-%m"));
	}
	else
	{
		strValue = dt.Format(_T("%Y-%d-%mT%H:%M:%S"));
	}

	return strValue;
}


你可能感兴趣的:(提供两个字符串与时间格式COleDateTime的转换)