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

MFC中时间相加减,格式化操作

2013年03月30日 ⁄ 综合 ⁄ 共 1392字 ⁄ 字号 评论关闭

今日工作需要记录文件路径和到期时间,用到了CTime类和CtimeSpan类进行时间的格式化和相加减操作。记录下来以备后用。

CTime的诸如GetDays()这些函数见名知义,不用记录。

CTime的Format函数原型为:

CString Format(
   LPCTSTR pszFormat 
) const;
CString Format(
   UINT nFormatID 
) const;
 

两个参数一个是传const char* 一个是传字符串ID。字符串中由formatting codes进行匹配时间,formatting codes可以在strftime下找到。贴在下面

%a

Abbreviated weekday name

%A

Full weekday name

%b

Abbreviated month name

%B

Full month name

%c

Date and time representation appropriate for locale

%d

Day of month as decimal number (01 – 31)

%H

Hour in 24-hour format (00 – 23)

%I

Hour in 12-hour format (01 – 12)

%j

Day of year as decimal number (001 – 366)

%m

Month as decimal number (01 – 12)

%M

Minute as decimal number (00 – 59)

%p

Current locale's A.M./P.M. indicator for 12-hour clock

%S

Second as decimal number (00 – 59)

%U

Week of year as decimal number, with Sunday as first day of week (00 – 53)

%w

Weekday as decimal number (0 – 6; Sunday is 0)

%W

Week of year as decimal number, with Monday as first day of week (00 – 53)

%x

Date representation for current locale

%X

Time representation for current locale

%y

Year without century, as decimal number (00 – 99)

%Y

Year with century, as decimal number

%z, %Z

Either the time-zone name or time zone abbreviation, depending on registry settings; no characters if time zone is unknown

%%

Percent sign

如果想要输出当前时间的年月日小时分钟可以使用如下代码

	CTime time = CTime::GetCurrentTime();
	CString strTime = time.Format("%Y-%m-%d %H:%M");
	AfxMessageBox(strTime);

和printf函数一样,支持使用#做前缀,例如月份前不想使用0进行补位,可以用%#m表示。

下面说日期的加减,CTime重载了+,-操作符,用来将CTime对象和CTimeSpan对象进行加减。用法如下

CTimeSpan timeSpan(35, 0, 0, 0);
time += timeSpan;

表示将time(CTime对象)加上35天0小时,0分,0秒。

抱歉!评论已关闭.