Search code examples
cstructcurrent-time

How to store the current date in a struct?


struct date{
  int date;
  int month;
  int year
};

struct date current_date;

I have this struct. Then I wanna store the current date in current_date. How can I do this using C language?

Thank You so much!


Solution

  • struct tm is a very standard structure for representing a broken down time representation with second resolution.

    You would:

    // get current time
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    // assign to your structure
    current_date.date = tm->tm_mday;
    current_date.month = tm->tm_mon + 1;
    current_date.year = tm->tm_mon + 1900;