C 语言中输出星期几364


在 C 语言中,我们可以使用 strftime 函数来格式化日期和时间,并输出星期几。该函数的原型如下:```c
int strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);
```

其中:* `str`:输出格式化后的字符串的缓冲区。
* `maxsize`:`str` 缓冲区的最大大小。
* `format`:格式化字符串,指定输出的格式。
* `timeptr`:指向一个 tm 结构体,其中包含了日期和时间的相关信息。

要输出星期几,我们可以使用 %a 或 %A 格式说明符。%a 输出星期几的缩写形式,而 %A 输出星期几的全称。例如:```c
#include
#include
int main() {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char buf[20];
strftime(buf, sizeof(buf), "%A", tm);
printf("Today is %s.", buf);
return 0;
}
```

上述代码将输出当前日期的星期几全称,例如:"Monday"。

我们还可以在 strftime 函数中使用其他格式说明符来输出更详细的日期和时间信息。例如:* `%Y`:输出年份。
* `%m`:输出月份(数字形式)。
* `%d`:输出日期。
* `%H`:输出小时(24 小时制)。
* `%M`:输出分钟。
* `%S`:输出秒。

我们可以将这些格式说明符组合起来,以输出所需的日期和时间格式。例如,以下代码将输出当前日期和时间,格式为:"2023-03-08 14:35:23":```c
#include
#include
int main() {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char buf[20];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
printf("Current date and time: %s.", buf);
return 0;
}
```

2024-11-25


上一篇:C 语言中函数的定义方法

下一篇:C 语言中函数的隐含类型