我想做的是获取当前系统日期和时间,并将它们保存到两个不同的变量中,以便稍后将它们与其他日期和时间进行比较。这是我到目前为止的代码。我的问题是,当我运行代码时,我一直得到相同的系统时间,它不正确,但日期是正确的。
#include <time.h>
#include <stdio.h>
int main() {
time_t raw;
time(&raw);
struct tm *time_ptr;
time_ptr = localtime(&raw);
char current_date[11];
char current_time [20];
strftime(current_date, sizeof(current_date), "%m/%d/%Y", time_ptr);
strftime(current_time, sizeof(current_time), "%H:%I", time_ptr);
printf("Date Variable is: %s\n", current_date);
printf("Time Variable is: %s\n", current_time);
}
最佳答案
您当时使用了错误的格式字符串。
%I
格式说明符为您提供 01-12 范围内的小时。所以 %H:%I
给你两次小时:第一次是 24 小时格式,然后是 12 小时格式。
如果想要分秒,需要分别使用%M
和%S
。
strftime(current_time, sizeof(current_time), "%H:%M:%S", time_ptr);
关于c - 在 C 编程中将当前日期和时间转换为 2 个不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41515876/