c - 在 C 编程中将当前日期和时间转换为 2 个不同的变量

标签 c date time

我想做的是获取当前系统日期和时间,并将它们保存到两个不同的变量中,以便稍后将它们与其他日期和时间进行比较。这是我到目前为止的代码。我的问题是,当我运行代码时,我一直得到相同的系统时间,它不正确,但日期是正确的。

#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/

相关文章:

c - C 中的动态 3D 可变列字符数组操作

java - Netbeans 可以定时执行吗?

objective-c - 选择器 'datetoday' 的闰年和 No Known Class 方法

c++ - 调用函数在 x 分钟内做任何事情

javascript - 如何以非常具体的方式 chop 字符串

c - 我如何忽略 C 中每行某个位置之后的字符?

c++ - 可以将Gtk +应用程序编译为在Gtk 2和3上运行

c - 用循环求平方根

php - PHP中的日期格式

python - 将时间戳转换为人类可读格式