C语言如何打印时间

文章介绍了Linux中获取和格式化时间的函数,包括time获取秒数,localtime和ctime将时间戳转化为易读格式,asctime进一步解释structtm结构体内容,以及gettimeofday用于获取微妙级别的精确时间。
摘要由CSDN通过智能技术生成

有库函数也有linux系统调用

  1. 第一个是time,参数可以为空,返回的是1970年1月1日0点到当前的时间的秒数,所以是很大的数字。
  2. 如果想清晰的看出年月日,时分秒,在time基础上,使用localtime函数,参数就是time返回值,localtime函数的返回值是一个结构体指针,结构体包含了年月日,时分秒,及周数天数等等。
  3. 如果感觉localtime打印这些时间太麻烦,可以使用asctime,它的作用,可以理解为直接帮你翻译结构体里面的内容,所以函数的参数就是struct time结构体。
  4. 还有个函数跟localtime功能差不多,ctime它可以直接把time得到的时间戳格式化。
  5. 如果你希望得到更加精准的时间,比如微妙这个级别,可以考虑使用gettimeofday,提供两个参数,第一个是struct timeval结构体,第二个参数可以写成空,timeval结构体包含了两个成员,一个是秒,一个是微妙,打印出来就是一个非常精确的时间。
#include<stdio.h>
#include<time.h>
#include<sys/time.h>

int main()
{
    time_t cur = time(NULL);
	printf("%lu\n", cur);
	
	printf("-----localtime-----\n");
	struct tm *t = localtime(&cur);
	printf("%d 年 %d 月 %d 日 %d 时 %d 分 %d 秒\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
    
	printf("-----asctime-----\n");
	printf("%s\n", asctime(t));
	
	printf("-----ctime-----\n");
	printf("%s\n", ctime(&cur));
	
	printf("-----gettimeofday-----\n");
	struct timeval t_val;
	gettimeofday(&t_val, NULL);
	printf("%ld %ld\n", t_val.tv_sec, t_val.tv_usec);

    return 0;
}

/*
1684857949
-----localtime-----
2023 年 5 月 23 日 12 时 5 分 49 秒
-----asctime-----
Tue May 23 12:05:49 2023

-----ctime-----
Tue May 23 12:05:49 2023

-----gettimeofday-----
1684857949 151647
*/

// 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) */
   // int tm_year;   /* Year - 1900 */
   // int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
   // int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
   // int tm_isdst;  /* Daylight saving time */
// };

// struct timeval {
   // time_t      tv_sec;     /* seconds */
   // suseconds_t tv_usec;    /* microseconds */
// };

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值