CTime 和CString的互相转换
CTime的格式有三种
short date:1990-10-10
long date:1990年10月1日
time: 8:30:10
引用
MSDN中CTime转换为CString
// example for CTime::Format and CTime::FormatGmt
CTime t( 1999, 3, 19, 22, 15, 0 );
// 10:15PM March 19, 1999
CString s = t.Format( “%A, %B %d, %Y” );
ASSERT( s == “Friday, March 19, 1999” );
时间的几种输出格式,其它格式要求见MSDN的strftime, wcsftime
//时间转字符
str = t.Format( “%A, %B %d, %Y” );//返回的是Wednesday,Jnuary 01,1992
//或者
str = t_birth.Format(VAR_DATEVALUEONLY);//1993-01-01
str =t.Format( “%x” ); //01/01/89
str = t.Format( “%X” ); //00:00:00
str = t.Format( “%Y年%m月%d日”);//1990年01月02日
str = t.Format( “%#Y年%#m月%#d日”);//1990年1月2日
str = t.Format( “%d年%02d月%02d日”,t.GetYear(),t.GetMonth(),
t.GetDay);());//1990年 1月 2日
#include "stdafx.h"
#include "CTimeAndCString.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CWinApp theApp;
using namespace std;
CString CTime2CString(CTime t)
{
CString s = t.Format( "%A, %B %d, %Y" );
return s;
}
CTime CString2CTime(CString str)
{
COleVariant vtime(str);
vtime.ChangeType(VT_DATE);
COleDateTime oletime=vtime;
SYSTEMTIME systime;
VariantTimeToSystemTime(oletime,&systime);
CTime time(systime.wYear,systime.wMonth,systime.wDay,systime.wHour,systime.wMinute,systime.wSecond);
return time;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
return nRetCode;
}
CTime t1 = CTime::GetCurrentTime();
CString s1 = CTime2CString(t1);
cout <<s1 <<endl;
cout << "当前时间转换为CString : "<<(LPCTSTR)s1 <<endl;
t1 = CString2CTime("1990-10-10");
cout <<t1.GetYear()<<"年"<<t1.GetMonth() <<"月"<< t1.GetDay() <<"日"<<t1.GetHour() <<"时"<<" 星期:"<<t1.GetDayOfWeek()<<endl;
t1 = CString2CTime("1990-10-11 8:30:10");
cout <<t1.GetYear()<<"年"<<t1.GetMonth() <<"月"<< t1.GetDay() <<"日"<<t1.GetHour() <<"时"<<t1.GetMinute()<<"分钟"<<t1.GetSecond()<<"秒"<<" 星期:"<<t1.GetDayOfWeek()<<endl;
t1 = CString2CTime("1992年12月12日");
cout <<t1.GetYear()<<"年"<<t1.GetMonth() <<"月"<< t1.GetDay() <<"日"<<t1.GetHour() <<"时"<<" 星期:"<<t1.GetDayOfWeek()<<endl;
return nRetCode;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
![运行结果](https://img-blog.csdn.net/20150802101157900)