c库函数之时间和日期处理

1. strptime

   函数原型:char *strptime(const char *buf,const char *format, struct tm *tm);

   功能:按照特定时间格式将字符串转换为时间类型。

   参数:buf  时间字符串指针;format  格式字符串指针;tm  保存转换后结果的时间结构体指针;

   返回值:调用成功返回 *buf最后位置,失败返回空指针。

  例子:

  

char fmt[] = "%Y-%m-%d-%H:%M:%S";
char buf[] = "2000-01-01-00:00:00";
struct tm tb;
if (strptime(buf, fmt, &tb) != NULL) 
{
  fprintf(stdout "ok");
}
 2.  localtime

  函数原型:struct tm *localtime(const time_t *clock);

  功 能: 把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,而gmtime函数转换后的时间没有经过时区变换,是UTC时间 。

  返回值:返回指向tm 结构体指针.tm结构体的时间是日历时间,tm结构体是time.h中定义的用于分别存储时间的各个量(年月日等)的结构体.

  例子1:

  

#include <stdio.h>
#include <stddef.h>
#include <time.h>
int main(void)
{
time_t timer;//time_t就是long int 类型
struct tm *tblock;
timer = time(NULL);
tblock = localtime(&timer);
printf("Local time is: %s\n",asctime(tblock));
return 0;
}
程序例2:
上面的例子用了asctime函数,下面这个例子不使用这个函数一样能获取系统当前时间。需要注意的是年份加上1900,月份加上1。

 
 
#include<time.h>
#include<stdio.h>
int main()
{
struct tm *t;
time_t tt;
time(&tt);
t=localtime(&tt);
printf("%4d年%02d月%02d日 %02d:%02d:%02d\n",t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
return 0;
}


3.gmtime

  原型:struct tm *gmtime(long *clock);

 功能:把日期和时间转换为格林威治(GMT)时间的函数。将参数timep 所指的time_t 结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果由结构tm返回。

返回值: 返回结构tm代表目前UTC 时间

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
};

int tm_sec 代表目前秒数,正常范围为0-59,但允许至61秒
int tm_min 代表目前分数,范围0-59
int tm_hour 从午夜算起的时数,范围为0-23
int tm_mday 目前月份的日数,范围01-31
int tm_mon 代表目前月份,从一月算起,范围从0-11
int tm_year 从1900 年算起至今的年数
int tm_wday 一星期的日数,从星期一算起,范围为0-6
int tm_yday 从今年1月1日算起至今的天数,范围为0-365
int tm_isdst 日光节约时间的旗标
此函数返回的时间日期未经时区转换,而是UTC时间。
例子:

  

#include "stdio.h"
#include "time.h"
#include "stdlib.h"
int main(void)
{
time_t t;
struct tm *gmt, *area;
tzset(); /*tzset()*/
t = time(NULL);
area = localtime(&t);
printf("Local time is: %s", asctime(area));
gmt = gmtime(&t);
printf("GMT is: %s", asctime(gmt));
return 0;
}
与localtime比较的不同点:

localtime函数获得的tm 结构体的时间,是已经进行过时区转化为本地时间。
而此函数功能类似获取当前系统时间,只是获取的时间未经过时区转换。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值