格式化一个时间字符串

王朝vc·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

格式化一个时间字符串

Article last modified on 2002-4-30

----------------------------------------------------------------

The information in this article applies to:

- Microsoft Visual C++ 6.0

----------------------------------------------------------------

利用Run-Time Library

具体的用法范例:

string strTime;

CurrentTimeStr(&strTime, TRUE);

CurrentTimeStr定义为:

#include <Time.h>

//////////////////////////////////////////////////////////////////////

//

// STL的常用头文件和声明:

//

//////////////////////////////////////////////////////////////////////

#pragma warning(disable:4786)

#include <string>

using namespace std;

//

//////////////////////////////////////////////////////////////////////

//

// 构造出当前时间的字符串

//

void CurrentTimeStr(string *pstrTimeString,

BOOL bWantMore)

{

char szTimeString[128];

memset(szTimeString, 0, 128);

使用的结构tm的说明:

在WCHAR.H中定义:

#ifndef _TM_DEFINED

struct tm {

int tm_sec; /* seconds after the minute - [0,59] */

int tm_min; /* minutes after the hour - [0,59] */

int tm_hour; /* hours since midnight - [0,23] */

int tm_mday; /* day of the month - [1,31] */

int tm_mon; /* months since January - [0,11] */

int tm_year; /* years since 1900 */

int tm_wday; /* days since Sunday - [0,6] */

int tm_yday; /* days since January 1 - [0,365] */

int tm_isdst; /* daylight savings time flag */

};

#define _TM_DEFINED

#endif

struct tm *today;

time_t类型是在WCHAR.H中定义:

#ifndef _TIME_T_DEFINED

typedef long time_t;

#define _TIME_T_DEFINED

#endif

time_t ltime;

定义在Time.H中

Set time zone from TZ environment variable. If TZ is not set,

the operating system is queried to obtain the default value

for the variable.

_tzset();

定义在Time.H中

Get UNIX-style time and display as number and string.

time( &ltime );

这个函数的定义是:

struct tm * __cdecl localtime(const time_t *);

它主要是用来Use time structure to build a customized time string and correct for the local time zone.

它将返回一个指针,指向tm的结构,如果这个时间值是早于1970年1月1日午夜的,则会返回NULL。

today = localtime( &ltime );

strftime指定的第一个参数就是目标字符串,第二个参数就是该目标字符串的最大

长度;

第三个参数将制定格式化的定义;

第四个参数是时间结构tm

下面说明格式化命令的含义:

%m

Month as decimal number (01 – 12)

%d

Day of month as decimal number (01 – 31)

%H

Hour in 24-hour format (00 – 23)

%M

Minute as decimal number (00 – 59)

%S

Second as decimal number (00 – 59)

strftime( szTimeString, 128,

"=时间: %m月%d日%H时%M分%S秒 ", today );

(*pstrTimeString).append(szTimeString);

}

//

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航