0

My program to find current system date and time is

#include<stdio.h>
#include<time.h>
struct date{
int day,month,year;
};
main()
{
    time_t t;
    time(&t);
    printf("Today's date and time is %s",ctime(&t));


}

and i want to store this current date to structure Please give me a suggestion of that.

  • 4
    Start by writing valid C. `int main(void)` and not `main()` – StoryTeller - Unslander Monica Feb 21 '17 at 07:23
  • I recommend you take a look at e.g. [this time function and structure reference](http://en.cppreference.com/w/c/chrono). – Some programmer dude Feb 21 '17 at 07:23
  • 1
    You should probably be planning to use [`localtime()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/localtime.html) or [`gmtime()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/gmtime.html), depending on whether you want local time or UTC. Note that you have to map the values — the year and month probably aren't the numbers you expect until you've read the manual carefully. – Jonathan Leffler Feb 21 '17 at 07:33
  • You can have a look here. [http://stackoverflow.com/questions/1442116/how-to-get-date-and-time-value-in-c-program](http://stackoverflow.com/questions/1442116/how-to-get-date-and-time-value-in-c-program) – rakesh sinha Feb 21 '17 at 07:35
  • _There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs._ – Sourav Ghosh Feb 21 '17 at 07:40

1 Answers1

3

The standard library already has a structure like yours: struct tm in <time.h>.

       int tm_sec;     /* seconds (0 - 60) */
       int tm_min;     /* minutes (0 - 59) */
       int tm_hour;    /* hours (0 - 23) */
       int tm_mday;    /* day of month (1 - 31) */
       int tm_mon;     /* month of year (0 - 11) */
       int tm_year;    /* year - 1900 */
       int tm_wday;    /* day of week (Sunday = 0) */
       int tm_yday;    /* day of year (0 - 365) */
       int tm_isdst;   /* is summer time in effect? */
       char *tm_zone;  /* abbreviation of timezone name */
       long tm_gmtoff; /* offset from UTC in seconds */

The library provides a global variable of type struct tm which is filled by the functions localtime (for your time zone) and gmtime (for GMT time).

C11 also specifies localtime_s and gmtime_s which avoid the issues associated with global variables, but I don't know how widely supported they are. POSIX also specifies the similar gmtime_r and localtime_r.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421