- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - localtime() 函数
C 库的 localtime() 函数用于处理与时间相关的任务,尤其是在用户希望以人类可读的格式显示时间信息时。
这里,struct tm *localtime(const time_t *timer) 使用 timer 指向的时间来填充一个 tm 结构,该结构包含表示对应本地时间的数值。timer 的值被分解到 tm 结构中,并以本地时区表示。
语法
以下是 C 库 localtime() 函数的语法:
struct tm *localtime(const time_t *timer)
参数
此函数仅接受一个参数:
- timer - 这是一个指向 time_t 值的指针,表示日历时间。
返回值
此函数返回一个指向 tm 结构的指针,其中填充了时间信息。
以下是 tm 结构的信息:struct tm {
int tm_sec; /* seconds, range 0 to 59 */
int tm_min; /* minutes, range 0 to 59 */
int tm_hour; /* hours, range 0 to 23 */
int tm_mday; /* day of the month, range 1 to 31 */
int tm_mon; /* month, range 0 to 11 */
int tm_year; /* The number of years since 1900 */
int tm_wday; /* day of the week, range 0 to 6 */
int tm_yday; /* day in the year, range 0 to 365 */
int tm_isdst; /* daylight saving time */
};
示例 1
以下是一个基本的 C 库程序,用于演示 localtime() 函数。
#include <stdio.h>
#include <time.h>
int main () {
time_t rawtime;
struct tm *info;
time( &rawtime );
info = localtime( &rawtime );
printf("Current local time and date: %s", asctime(info));
return(0);
}
输出
执行上述代码后,我们将得到以下结果:
Current local time and date: Tue May 14 10:01:48 2024
示例 2
下面的程序说明了如何使用 time() 函数获取当前时间,以及如何使用 localtime() 函数显示结果。
#include <stdio.h>
#include <time.h>
int main()
{
time_t current_time;
// get the current time using time()
current_time = time(NULL);
// call the function localtime() that takes timestamp and convert it into localtime representation
struct tm *tm_local = localtime(¤t_time);
// corresponding component of the local time
printf("Current local time : %d:%d:%d", tm_local -> tm_hour, tm_local -> tm_min, tm_local -> tm_sec);
return 0;
}
输出
上述代码产生以下结果:
Current local time : 11:36:56
示例 3
在处理当前日期的任务时,它使用 localtime() 提供日期,并使用 strftime() 显示格式化的结果。
#include <stdio.h>
#include <time.h>
int main(void) {
size_t maxsize = 80;
char dest[maxsize];
time_t now;
struct tm *tm_struct;
time(&now);
tm_struct = localtime(&now);
strftime(dest, maxsize, "%D", tm_struct);
printf("Current date: %s\n", dest);
return 0;
}
输出
执行代码后,我们将得到以下结果:
Current date: 05/17/24
广告