C语言中的时间函数localtime和gmtime

localtime和gmtime这两个函数采用了time.h中的一个tm结构体:

struct tm
{
  int tm_sec;           /* Seconds. [0-60] (1 leap second) */
  int tm_min;           /* Minutes. [0-59] */
  int tm_hour;          /* Hours.   [0-23] */
  int tm_mday;          /* Day.     [1-31] */
  int tm_mon;           /* Month.   [0-11] */
  int tm_year;          /* Year - 1900.  */
  int tm_wday;          /* Day of week. [0-6] */
  int tm_yday;          /* Days in year.[0-365] */
  int tm_isdst;         /* DST.     [-1/0/1]*/

#ifdef  __USE_BSD
  long int tm_gmtoff;       /* Seconds east of UTC.  */
  __const char *tm_zone;    /* Timezone abbreviation.  */
#else
  long int __tm_gmtoff;     /* Seconds east of UTC.  */
  __const char *__tm_zone;  /* Timezone abbreviation.  */
#endif
};


这两个函数的原型为:

struct tm *localtime(const time_t *timep);

struct tm *gmtime(const time_t *timep);



 

具体实现为:

localtime.c

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

#include <stdio.h>
#include <time.h>
void cur_time(void);

int main(int argc,char **argv)
{   
cur_time();

return 0;
}

void cur_time(void)
{
    char *wday[]={"星期天","星期一","星期二","星期三","星期四","星期五","星期六"};
    time_t timep;
    struct tm *p;
    time(&timep);
    p=localtime(&timep);  /* 获取当前时间 */
    printf("%d年%02d月%02d日",(1900+p->tm_year),(1+p->tm_mon),p->tm_mday);
    printf("%s %02d:%02d:%02d\n",wday[p->tm_wday],p->tm_hour,p->tm_min,p->tm_sec);
}


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


 

gmtime.c

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

#include <stdio.h>
#include <time.h>
void cur_time(void);

int main(int argc,char **argv)
{
  cur_time();
  return 0;
}

void cur_time(void)
{
    char *wday[]={"星期天","星期一","星期二","星期三","星期四","星期五","星期六"};
    time_t timep;
    struct tm *p;
    time(&timep);
    p=gmtime(&timep);  /* 获取当前时间 */
    printf("%d年%02d月%02d日",(1900+p->tm_year),(1+p->tm_mon),p->tm_mday);
    printf("%s %02d:%02d:%02d\n",wday[p->tm_wday],(p->tm_hour+8),p->tm_min,p->tm_sec);
}


展开阅读全文

没有更多推荐了,返回首页