我的 C 项目中有一个问题,涉及各种时间表,每个时间表都需要一个日期。我使用结构获得它。现在我想删除所有旧的时间表,因此为了做到这一点,代码需要:
- 获取当前时间
- 运行我的列表来比较是否(日期(现在)> 日期(旧))。如果为 true,代码将删除相关的计划。
主要问题涉及如何获取实时并将其传递给我的结构。有人可以在这方面提供帮助吗?
尝试获取实时并将其放入结构中的代码如下:
#include <stdio.h>
#include <time.h>
typedef struct date Date;
typedef struct hour Hour;
struct hour{
int hour;
int minute;
int second;
};
struct date{
int day;
int month;
int year;
Hour hour;
};
int main (void) {
Date date;
//char buff[100];
time_t now = time(0);
strftime (date, 100, "%d-%m-%Y %H:%M:%S", localtime(&now));
printf ("%s\n", date);
//I want to put localtime(&now) on date instead buff that is a char!
//To me compare after
return 0;
}
最佳答案
使用struct tm
与localtime
一起获取日、月、年等的各个值。然后,您可以将这些值复制到您自己的结构中,也可以在代码中直接使用 struct tm 。请注意,在复制到结构时,如果您想要将 2017
作为年份值而不是 117
,则需要调整某些值:
int main (void) {
Date date;
char buff[100];
time_t now = time(0);
struct tm now_t = *localtime(&now);
strftime (buff, 100, "%d-%m-%Y %H:%M:%S", &now_t);
date.year = now_t.tm_year + 1900; // years since 1900
date.month = now_t.tm_mon + 1; // months since January [0-11]
date.day = now_t.tm_mday; // day of month [1-31]
date.hour.hour = now_t.tm_hour;
date.hour.minute = now_t.tm_min;
date.hour.second = now_t.tm_sec;
return 0;
}
关于C - 如何在 C 中使用结构体获取时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44768107/