C语言中有关时间的函数汇总

来源:互联网 发布:java做cs 编辑:程序博客网 时间:2024/06/07 01:30

函数:time;localtime;gmtime;ctime;asctime;

1)time

time()函数声明位于time.h中,

原型是:time_t time(time *timeptr)

作用是:

返回1970-1-1日0时0分0秒到调用时刻的时长,如果参数不是空指针,那么返回值也会存储到参数自变量指向的位置。就是我们常说的日历时间。

#include <stdio.h>#include <stddef.h>#include <time.h>
int main(void)
{time_t timer;struct tm *tblock;timer = time(NULL);printf("%08X\n",timer);tblock = localtime(&timer);printf("Local time is: %s\n",asctime(tblock));return 0;}
 

localtime()函数声明位于time.h中

原型是:struct tm *localtime(const time_t *timer);

作用是:

将日历时间(1970-1-1日0时0分0秒开始的时长)转换为本地时区的日期和时间结构。些函数的参数不是秒数本身,而是一个指向此数值的指针,成功调用此函数后可以通过struct tm结构体的各成员访问传入参数对应的本地时间

struct   tm
{
      int   tm_sec;            /*0-59的秒数*/
      int   tm_min;            /* 0-59的分数 */
      int   tm_hour;         /* 0-23的小时数 */
      int   tm_mday;       /*1-31的日期数*/
      int   tm_mon;         /*0-11的月数*/
      int   tm_year;         /* 1900~至今的年数 */
      int   tm_wday;       /*0-6的星期数*/
      int   tm_yday;       /*0-365的天数*/
      int   tm_isdst;       /*日光节约
};
 
#include <stdio.h>
#include <time.h>
int main(int argc,char **argv)
{ 

time_t timep; struct tm *localp; struct tm *gmp; timep=time(NULL); localp=localtime(&timep); /* 获取当前时间 */ gmp=gmtime(&timep); /* 获取当前时间 */

 printf("%x\n",timep);  printf("localtime:%2d-%02d-%02d %02d:%02d:%02d\n",(1900+localp->tm_year),  (1+localp->tm_mon),localp->tm_mday,localp->tm_hour,  localp->tm_min,localp->tm_sec);//注意这里年+1900,月+1  

 printf("gmtime:   %2d-%02d-%02d %02d:%02d:%02d\n",(1900+gmp->tm_year),  (1+gmp->tm_mon),gmp->tm_mday,gmp->tm_hour,  gmp->tm_min,gmp->tm_sec);//注意这里年+1900,月+1 

 printf("local today's date and time(asctime): %s\n", asctime(localp)); //打印日志时间。 printf("gm today's date and time(asctime): %s\n", asctime(gmp)); //打印日志时间。    printf("time today's date and time: %s\n", ctime(&timep)); //打印日志时间。

return 0;

}
 
输出:

4f23baff

localtime:2012-01-28 09:08:15gmtime:   2012-01-28 09:08:15

local today's date and time(asctime): Sat Jan 28 09:08:15 2012

gm today's date and time(asctime): Sat Jan 28 09:08:15 2012

time today's date and time: Sat Jan 28 17:08:15 2012

 

 

 

 

 

原创粉丝点击