- 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库 - asctime() 函数
C库 asctime() 函数返回一个指向字符串的指针,该字符串表示结构体 struct timeptr 的日期和时间。此函数用于将日历时间表示为人类可读的字符串。
语法
以下是C库 asctime() 函数的语法:
char *asctime(const struct tm *timeptr)
参数
timeptr 是指向 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 */
};
返回值
此函数返回一个C字符串,其中包含以人类可读的格式 Www Mmm dd hh:mm:ss yyyy 表示的日期和时间信息,其中 Www 是星期几,Mmm 是月份的字母缩写,dd 是月份中的第几天,hh:mm:ss 是时间,yyyy 是年份。
示例1
以下是 asctime() 函数的简单C库程序。
#include <stdio.h>
#include <string.h>
#include <time.h>
int main () {
struct tm t;
t.tm_sec = 10;
t.tm_min = 10;
t.tm_hour = 6;
t.tm_mday = 25;
t.tm_mon = 2;
t.tm_year = 89;
t.tm_wday = 6;
puts(asctime(&t));
return(0);
}
输出
以上代码产生以下结果:
Sat Mar 25 06:10:10 1989
示例2
为了获得当前/本地时间,我们使用 localtime() 函数生成时钟的本地时间,然后调用 asctime() 函数来显示它。
#include <stdio.h>
#include <time.h>
int main() {
struct tm* ptr;
time_t lt;
lt = time(NULL);
ptr = localtime(<);
printf("Current local time: %s", asctime(ptr));
return 0;
}
输出
执行上述代码后,我们将得到以下结果:
Current local time: Tue May 14 07:00:11 2024
示例3
此C程序使用 asctime() 函数和(如果可用)asctime_s() 函数以人类可读的格式显示当前本地时间。
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <time.h>
int main(void) {
struct tm tm = *localtime(&(time_t){time(NULL)});
printf("Current local time (using asctime()): %s\n", asctime(&tm));
#ifdef __STDC_LIB_EXT1__
char str[50];
asctime_s(str, sizeof str, &tm);
printf("Current local time (using asctime_s()): %s\n", str);
#endif
return 0;
}
输出
执行上述代码后,我们将得到以下结果:
Current local time (using asctime()): Tue May 14 07:09:57 2024
广告