时间相关函数

本文介绍了如何在C语言中使用time(),ctime(),localtime()和asctime()函数来获取、转换和格式化世界标准时间(格林尼治时间),包括获取标准时间、字符串时间表示以及本地时间处理。
摘要由CSDN通过智能技术生成

世界标准时间:指的是格林尼治时间,从1970年1月1日凌晨零点零分零秒 到 此时此刻的秒数。

        头文件:#include <time.h>

1.获取标准时间:

        time_t  time(time_t *tloc);

        参数  ----- 保存时间的变量的地址;
        返回值 --成功:秒数,失败:-1;

#include <stdio.h>
#include <time.h>
int main(void)
{
    time_t tm1,tm2;


    tm2 = time(&tm1);
    printf("tm1 = %ld\n",tm1);
    printf("tm2 = %ld\n",tm2);

    return 0;
}

运行结果:

2.将标准时间转为字符串格式的时间:

        char *ctime(const time_t *timep);
        参数  ---- 以秒为单位的时间;
        返回值 ---- 成功:字符串时间,失败:NULL;

#include <stdio.h>
#include <time.h>
int main(void)
{
    time_t tm1;
    time(&tm1);
    printf("%s",ctime(&tm1));

    return 0;
}

运行结果:

3.将标准时间转为本地时间

        struct tm *localtime(const time_t *timep);
        参数 -----以秒为单位的数时间;
        返回值  ----成功:结构体指针(struct tm),失败:NULL;

struct tm 
{
    int tm_sec;    /* Seconds (0-60) */
    int tm_min;    /* Minutes (0-59) */
    int tm_hour;   /* Hours (0-23) */
    int tm_mday;   /* Day of the month (1-31) */
    int tm_mon;    /* Month (0-11) *///使用时+1
    int tm_year;   /* Year - 1900 */
    int tm_wday;   /* Day of the week (0-6, Sunday = 0) */使用时+1
    int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
    int tm_isdst;  /* Daylight saving time */
};
#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t tm1;
    struct tm *tp;

    time(&tm1);
    tp = localtime(&tm1);
    printf(GREEN"[%04d - %02d - %02d]  %02d : %02d : %02d \n "NONE,\
            tp->tm_year+1900,tp->tm_mon+1,tp->tm_mday,\
            tp->tm_hour,tp->tm_min,tp->tm_sec);

    return 0;
}

运行结果:

4.本地时间转为字符串时间

        char *asctime(const struct tm *tm);
        参数 --- 结构体指针(struct tm)
        返回值 ---- 成功:字符串时间,失败:NULL

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

int main(void)
{
    time_t tm1;
    struct tm *tp;

    time(&tm1);
    tp = localtime(&tm1);
    printf(GREEN"[%04d - %02d - %02d]  %02d : %02d : %02d \n "NONE,\
            tp->tm_year+1900,tp->tm_mon+1,tp->tm_mday,\
            tp->tm_hour,tp->tm_min,tp->tm_sec);
    printf(RED"%s"NONE,asctime(tp));

    return 0;
}

 运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值