C语言中获取时间的函数339


在C语言中获取系统时间的函数有以下几个:1. time() 函数

time() 函数返回自纪元以来经过的秒数。纪元通常是 1970 年 1 月 1 日午夜 (UTC)。```c
#include
time_t time(time_t *t);
```
* 参数:
* `t`: 一个可选的指针,用于存储当前时间。
* 返回值: 自纪元以来经过的秒数。如果发生错误,则返回 -1。
2. localtime() 函数

localtime() 函数将 time() 函数返回的秒数转换为 struct tm 格式的本地时间。```c
#include
struct tm *localtime(const time_t *timep);
```
* 参数:
* `timep`: 一个指向 time() 函数返回的秒数的指针。
* 返回值: 一个指向 struct tm 结构体的指针,其中包含本地时间信息。
3. strftime() 函数

strftime() 函数将 struct tm 结构体中的时间信息格式化为字符串。```c
#include
size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *timeptr);
```
* 参数:
* `s`: 要写入格式化字符串的缓冲区。
* `maxsize`: 缓冲区的大小。
* `format`: 一个格式化字符串,指定如何格式化时间。
* `timeptr`: 一个指向 struct tm 结构体的指针,其中包含时间信息。
* 返回值: 写入缓冲区中的字符数。
4. gmtime() 函数

gmtime() 函数与 localtime() 函数类似,但它返回的是格林威治标准时间 (GMT)。```c
#include
struct tm *gmtime(const time_t *timep);
```
* 参数:
* `timep`: 一个指向 time() 函数返回的秒数的指针。
* 返回值: 一个指向 struct tm 结构体的指针,其中包含 GMT 时间信息。
5. mktime() 函数

mktime() 函数将 struct tm 结构体中的时间信息转换为时间戳(自纪元以来经过的秒数)。```c
#include
time_t mktime(struct tm *timeptr);
```
* 参数:
* `timeptr`: 一个指向 struct tm 结构体的指针,其中包含时间信息。
* 返回值: 自纪元以来经过的秒数。如果发生错误,则返回 -1。
示例:
```c
#include
#include
#include
int main() {
time_t t = time(NULL);
struct tm *local = localtime(&t);
printf("当前日期:%d-%d-%d", local->tm_year + 1900, local->tm_mon + 1, local->tm_mday);
printf("当前时间:%d:%d:%d", local->tm_hour, local->tm_min, local->tm_sec);
return 0;
}
```
输出:
```
当前日期:2023-03-17
当前时间:15:30:00
```

2024-12-04


上一篇:C 语言中的延时函数

下一篇:C 语言中倒序输出数据结构