C++ C字符串与time_c和time_c与C字符串之间的转换
http://cyanman.blog.163.com/blog/static/15250208200892501645480/
方法1, SYSTEMTIME 类型
//指定time_t类型的时间,格式化为YYYYMMDDHH24MISS型的字符串
void FormatTime(SYSTEMTIME &tm1)
{
TCHAR * szTime = new TCHAR[128];
GetLocalTime(&tm1);
_stprintf( szTime, _T("%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d"),
tm1.wYear, tm1.wMonth+1, tm1.wDay,
tm1.wHour, tm1.wMinute,tm1.wSecond);
delete szTime;
szTime = NULL;
}
//指定YYYYMMDDHH24MISS型的时间,格式化为time_t型的时间
SYSTEMTIME FormatTime2(TCHAR * szTime)
{
SYSTEMTIME tm1;
_stscanf( szTime, _T("%4d-%2d-%2d %2d:%2d:%2d"),
&tm1.wYear,
&tm1.wMonth,
&tm1.wDay,
&tm1.wHour,
&tm1.wMinute,
&tm1.wSecond );
return time1;
}
方法2, time_t类型
//指定time_t类型的时间,格式化为YYYYMMDDHH24MISS型的字符串
void FormatTime(time_t time1, char *szTime)
{
struct tm tm1;
#ifdef WIN32
tm1 = *localtime(&time1);
#else
localtime_r(&time1, &tm1 );
#endif
sprintf( szTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d",
tm1.tm_year+1900, tm1.tm_mon+1, tm1.tm_mday,
tm1.tm_hour, tm1.tm_min,tm1.tm_sec);
}
//指定YYYYMMDDHH24MISS型的时间,格式化为time_t型的时间
time_t FormatTime2(char * szTime)
{
struct tm tm1;
time_t time1;
sscanf(szTime, "%4d%2d%2d%2d%2d%2d",
&tm1.tm_year,
&tm1.tm_mon,
&tm1.tm_mday,
&tm1.tm_hour,
&tm1.tm_min,
&tm1.tm_sec);
tm1.tm_year -= 1900;
tm1.tm_mon --;
tm1.tm_isdst=-1;
time1 = mktime(&tm1);
return time1;
}