C - 如何在 C 中使用结构体获取时间

标签 c struct

我的 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 tmlocaltime 一起获取日、月、年等的各个值。然后,您可以将这些值复制到您自己的结构中,也可以在代码中直接使用 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/

相关文章:

c - 寻找重叠的算法

c - 删除c中链表中最后一项的问题

go - 从数据 golang slice 初始化创建 Struct 实例

c# - 从 C 函数返回结构,C# 中的等价物是什么?

go - 如何将 interface{} 转换回其原始结构?

c - 构建交叉编译器 - 错误 : libmpfr not found

c - 一对变量/结构的偏移量是否相同?

c - 如何在 C 中将这些 ASCII 值转换为二进制

c++ - 在 C 中使用指针时出现段错误

c - 我的跳过列表真的是在 N 而不是 log(N) 中搜索吗?