应用编程——时间编程

3、时间编程

3.1、获取标准时间

#include <time.h>
time_t time(time_t *t);   //获取标准时间:从1970年1月1日凌晨零点零分零秒到此时此刻的秒数
//参数1: ----- 保存秒数变量的地址
//返回值:成功--返回获取的秒数,失败-- -1 

3.2、将标准时间转换为字符串

char *ctime(const time_t *timep);
//标准时间的指针
//返回值:成功--字符串时间,失败--  -1

3.3、将标准时间转换为本地时间

struct tm *localtime(const time_t *timep);

本地时间对应一个结构体:
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] :冬令时间或夏令时间 */
};

3.4、将本地时间转换为字符串时间

char *asctime(const struct tm *tm);

综合例子

#include <stdio.h>
#include <time.h>

int main()
{
    time_t tm,m;
    struct tm *ptm;

    //获取标准时间
    m = time(&tm);
    printf("tm = %lu\n",tm);
    printf("m = %lu\n",m);

    //将标准时间按转换成字符串
    printf("%s",ctime(&tm));
    
    //将标准时间转换成本地时间
    ptm = localtime(&tm);
    printf("%04d-%02d-%02d %02d:%02d:%02d\n",ptm->tm_year+1900,ptm->tm_mon+1,ptm->tm_mday,\
	    ptm->tm_hour,ptm->tm_min,ptm->tm_sec);

    //把本地时间转换为字符串格式的时间
    printf("%s",asctime(ptm));	    
    return 0;
}

//运行结果
esdon@ubuntu:/mnt/hgfs/tolinux/IOprogram/TestCode$ ./time
tm = 1617252580
m = 1617252580
Wed Mar 31 21:49:40 2021
2021-03-31 21:49:40
Wed Mar 31 21:49:40 2021
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值