C语言获取当前系统时间,精确到秒

本文详细介绍了C语言中time和localtime函数的使用方法,包括如何获取当前时间戳、转换为本地时间和格式化输出。通过具体代码示例展示了从1970年1月1日至今的秒数计算及日期时间的展示。

#include<time.h>

#include<stdio.h>

 int main(void){
       time_t now ;
       struct tm *tm_now ;
       time(&now) ;
       tm_now = localtime(&now) ;//get date
  printf("start datetime: %d-%d-%d %d:%d:%d\n",tm_now->tm_year+1900, tm_now->tm_mon+1, tm_now->tm_mday, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec) ;

       sleep(3);

       time(&now) ;

       tm_now = localtime(&now) ;//get date
  printf("end datetime: %d-%d-%d %d:%d:%d\n",tm_now->tm_year+1900, tm_now->tm_mon+1, tm_now->tm_mday, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec) ;

      return 0;

}

实验结果:

可以通过time()函数来获得计算机系统当前的日历时间(Calendar Time),处理日期时间的函数都是以本函数的返回值为基础进行运算。

1. time 函数

    返回1970-1-1, 00:00:00以来经过的秒数

    原型: time_t time(time_t *calptr)

         结果可以通过返回值,也可以通过参数得到,见实例

    头文件 <time.h>

    返回值:

        成功:秒数,从1970-1-1,00:00:00 可以当成整型输出或用于其它函数

        失败:-1

    例:

      time_t now;

      time(&now);// 等同于now = time(NULL)

      printf("now time is %d\n", now);

 

程序例:

#include

int main(void)

{

time_t t;

t=time(NULL);

printf("The number of seconds since January 1, 1970 is  %d\n",t);

return 0;

}

运行的结果与当时的时间有关,我当时运行的结果是:

The Calendar Time now is 1266637045

 

其中1266637045就是我运行程序时的日历时间。即从197011000秒到此时的秒数。

6行中给time函数的参数设置为NULL,可得到具体的秒数。

可将第6行改写为以下形式:

time(&t);

变量t中存放当前的日期和时间(相当于函数返回值);如果想要将这得到日历时间,就需要用到localtime函数,如下:

 

2. localtime函数

    将时间数值变换成本地时间,考虑到本地时区和夏令时标志;

    原型: struct tm *localtime(const time_t * calptr);

    头文件 <time.h>

 返回值:

        成功: struct 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代表一月) - 取值区间为[0,11] */

                   int tm_year;     /* 年份,其值等于实际年份减去1900 */

                   int tm_wday;    /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一 */

                   int tm_yday;    /* 从每年1月1日开始的天数– 取值区间[0,365],其中0代表1月1日 */

                   int tm_isdst;    /* 夏令时标识符,夏令时tm_isdst为正;不实行夏令时tm_isdst为0 */    

            };

                此结构体空间由内核自动分配, 而且不要去释放它.

        失败: NULL

转载于:https://my.oschina.net/u/3548719/blog/1576814

<think>我们使用gettimeofday函数来获取当前时间(精确到微秒) 然后通过localtime函数将秒数转换为本地时间结构体 最后将时间格式化为我们需要的字符串,并包含毫秒部分(注意:微秒除以1000得到毫秒) 注意:gettimeofday函数在sys/time.h头文件中 步骤: 1. 包含必要的头文件:<stdio.h>, <time.h>, <sys/time.h> 2. 声明struct timeval类型的变量tv和struct timezone类型的变量tz(虽然时区信息通常用不到,但函数需要) 3. 调用gettimeofday(&tv, &tz)获取当前时间 4. 使用localtime函数将tv.tv_sec(秒数)转换为struct tm结构体 5. 使用strftime函数将struct tm格式化为字符串(精确到秒的部分) 6. 将微秒(tv.tv_usec)转换为毫秒(tv.tv_usec/1000) 7. 输出格式化后的字符串和毫秒部分 注意:时区信息我们这里不关心,可以传入NULL,即gettimeofday(&tv, NULL) 下面是一个示例代码:</think>在 Linux 环境下使用 C 语言获取当前时间并精确到毫秒,可通过 `gettimeofday()` 函数实现。以下是详细步骤和代码示例: ### 解决方案 1. **包含头文件**: ```c #include <stdio.h> #include <sys/time.h> // 提供 gettimeofday() #include <time.h> // 提供 localtime() 和 strftime() ``` 2. **使用 `gettimeofday()` 获取时间**: - 该函数返回 `struct timeval`,包含: - `tv_sec`:自 1970-01-01 00:00:00 UTC 起经过的秒数 - `tv_usec`:当前秒内的微秒数(毫秒 = `tv_usec / 1000`) 3. **转换为本地时间格式**: - 用 `localtime()` 将 `tv_sec` 转为本地时间的 `struct tm` - 用 `strftime()` 将 `struct tm` 格式化为字符串 ### 完整代码示例 ```c #include <stdio.h> #include <sys/time.h> #include <time.h> int main() { struct timeval tv; struct tm *local_time; char time_str[32]; // 1. 获取精确时间(微秒级) gettimeofday(&tv, NULL); // 第二个参数时区通常传NULL // 2. 将秒数转换为本地时间结构 local_time = localtime(&tv.tv_sec); // 3. 格式化日期时间精确到秒) strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", local_time); // 4. 输出结果(毫秒 = 微秒/1000) printf("当前时间(毫秒): %s.%03ld\n", time_str, tv.tv_usec / 1000); return 0; } ``` ### 输出示例 ``` 当前时间(毫秒): 2023-10-05 14:30:45.789 ``` ### 关键说明 1. **`gettimeofday()`** 直接获取系统时间戳,精度达微秒级(`struct timeval`)[^2][^3]。 2. **毫秒计算** 通过 `tv.tv_usec / 1000` 将微秒转换为毫秒(整数除法)。 3. **时间格式化** `strftime()` 的格式说明符: - `%Y`:4位数年份 - `%m`:月份(01-12) - `%d`:日期(01-31) - `%H`:小时(00-23) - `%M`:分钟(00-59) - `%S`:秒(00-59) ### 注意事项 - 时区处理:`localtime()` 自动根据系统时区转换 UTC 时间。 - 性能:`gettimeofday()` 是系统调用,频繁调用可能影响性能。 - 更高精度:如需纳秒级精度,可使用 `clock_gettime(CLOCK_REALTIME, &ts)`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值