c语言库函数:时间相关time,localtime,asctime

目录

1.引言

2.时间函数基本信息

2.1 time函数

2.2 local函数

2.3 asctime函数

3.使用demo


1.引言

很多时候,我们需要使用当前时间,怎么获取呢?其实c语言库函数中提供了一些列时间相关的函数,可以从系统中获取时间的方法。今天我们就熟悉一下相关函数吧,并提供获取本地时间的demo.

2.时间函数基本信息

2.1 time函数

头文件
#include<time.h>

函数原型
time_t time(time_t *seconds)
参数说明
seconds -- 这是指向类型为 time_t 的对象的指针,用来存储 seconds 的值
返回值

尽管 C 标准没有定义,它几乎总是一个保有从纪元开始秒数的整数值(不计闰秒),对应成功时返回编码成 time_t 对象的当前日历时间。错误时返回 (time_t)(-1) 。若seconds不是空指针,则返回值也会存储于 arg 所指向的对象。
time_t数据结构
typedef /* unspecified */ time_t; //暂时未指定

2.2 local函数

头文件
#include<time.h>

函数原型
struct tm *localtime( const time_t *time );
参数说明
time—转换从纪元开始的给定时间( 常常是time函数返回的time_t 的值),以 struct tm 格式及本地时间表达的日历时间。存储结果于静态存储,并返回指向静态存储的指针。
返回值
成功时为指向内部静态 struct tm 对象的指针,否则为 NULL 。

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;       /* 夏令时                */
};

2.3 asctime函数

头文件
#include<time.h>
函数原型
char* asctime( const struct tm* time_ptr );
功能
将给定的日历时间 *time_ptr 转换成下列固定的 25 字符文本返回字符数组中

Www Mmm dd hh:mm:ss yyyy\n 
Www - 三字母英文星期缩写,

来自 time_ptr->tm_wday ,为 Mon 、 Tue 、 Wed 、 Thu 、 Fri 、 Sat 、 Sun 之一。
Mmm - 三字母英文月份缩写,

来自 time_ptr->tm_mon,为 Jan 、 Feb 、 Mar 、 Apr 、 May 、 Jun 、 Jul 、 Aug 、 Sep 、 Oct 、 Nov 、 Dec 之一。
dd - 月份日期的 2 位数字,

来自 time_ptr->tm_mday ,如 sprintf 用 %2d 打印。
hh - 小时的 2 位数字,

来自 time_ptr->tm_hour ,如 sprintf 用 %.2d 打印。
mm - 分的 2 位数字,

来自 time_ptr->tm_min ,如 sprintf 用 %.2d 打印。
ss - 秒的 2 位数字,

来自 time_ptr->tm_sec ,如 sprintf 用 %.2d 打印。
yyyy - 年的 4 位数字,

来自 time_ptr->tm_year + 1900 ,如 sprintf 用 %4d 打印。

3.使用demo

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


int main(int argn, char* argv[])
{
    time_t tm1;
    //为了使用localtime返回的存放静态时间日期的资源指针
    struct tm* ptm;
    //获取时间,据某个历史时间的秒数
    tm1 = time(NULL);
    ptm = localtime(&tm1);
    //打印,其中asctime是为了把tm结构体的资源变成字符串
    printf("hello tm1:%ld\n",tm1);
    printf("hello ptm:\n%s\n",asctime(ptm));
    return 0;
}

编译

g++ time_demo.cpp -o time_demo

运行

 ./time_demo

结果如下

root@xuehaiyang:/mnt/hgfs/99_github/cpp_demo# ./time_demo
hello tm1:1712334446
hello ptm:
Sat Apr  6 00:27:26 2024

  • 21
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青草地溪水旁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值