C, time, day of month, year and more
c, cross-platform, time
Solution
`localtime_r` is not part of the C standard. Maybe you were looking for `localtime`?
`localtime_r` is really available on many linux systems:
Thread-safe versions asctime_r(), ctime_r(), gmtime_r() and localtime_r() are specified by SUSv2, and available since libc 5.2.5
However, since it isn't part of the standard you cannot use it on Windows.
How can I change this to date format like this: 5.12.2012 or 5-12-2012? And how to get the day of the year?
You have to use `strftime` instead of `asctime`:
int main ()
{
time_t time_raw_format;
struct tm * ptr_time;
char buffer[50];
time ( &time_raw_format );
ptr_time = localtime ( &time_raw_format );
if(strftime(buffer,50,"%d.%m.%Y",ptr_time) == 0){
perror("Couldn't prepare formatted string");
} else {
printf ("Current local time and date: %s", buffer);
}
return 0;
}
Problem
I've got a problem. I need to get things like day of year, day of month, month of year etc. I use this code: ``` #include <stdio.h> #include <time.h> int main(void) { time_t liczba_sekund; struct tm strukt; time(&liczba_sekund); localtime_r(&liczba_sekund, &strukt); printf("today is %d day of year\nmonth is %d, month's day %d\n", strukt.tm_yday+1, strukt.tm_mon+1, strukt.tm_mday); return 0; } ``` First thing: why does gcc -std=c99 -pedantic -Wall return this warning: My input: gcc test_data.c -o test_data.out -std=c99 -pedantic -Wall Output: test_data.c: In function ‘main’: test_data.c:11:3: warning: implicit declaration of function ‘localtime_r’ [-Wimplicit-function-declaration] Second thing: how to make it work on windows? While trying to compile it using Dev-C, I got this: https://i.stack.imgur.com/F8Qlx.jpg @@EDIT -------------------- I have found an example for your localtime suggestion: ``` #include <stdio.h> #include <time.h> int main () { time_t time_raw_format; struct tm * ptr_time; time ( &time_raw_format ); ptr_time = localtime ( &time_raw_format ); printf ("Current local time and date: %s", asctime(ptr_time)); return 0; } ``` How can I change this to date format like this: 5.12.2012 or 5-12-2012? And how to get the day of the year? I would love if the solution worked both on windows and linux.