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日
// CTimeAndCString.cpp : Defines the entry point for the console application.
/********************************************************************
程序:CTime 和CString的互相转换
编译器:vc6.0
作者:斩月
时间:10:07 2015-8-2
使用说明:建立Win32命令行程序,工程名CTimeAndCString,勾选MFC
*********************************************************************/
#include "stdafx.h"
#include "CTimeAndCString.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
CWinApp theApp;
using namespace std;
CString CTime2CString(CTime t)
{
CString s = t.Format( "%A, %B %d, %Y" );
//ASSERT( s == "Friday, March 19, 1999" );
return s;
}
CTime CString2CTime(CString str)
{
COleVariant vtime(str);
vtime.ChangeType(VT_DATE);
COleDateTime oletime=vtime; //vtime = 1983-1-1
SYSTEMTIME systime;
VariantTimeToSystemTime(oletime,&systime);
//CTime time(oletime); //这一步转换的可能有误,替换成下面的程序
CTime time(systime.wYear,systime.wMonth,systime.wDay,systime.wHour,systime.wMinute,systime.wSecond); //CTime time(1990,1,1,0,0,0);
return time;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
return nRetCode;
}
CTime t1 = CTime::GetCurrentTime(); //ti = 1438478336
CString s1 = CTime2CString(t1); //返回值是 Sunday, August 02, 2015
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;
}