How to find the current day in c-language?

I can get the current date, but the result is similar to 9/1/2010, but my requirement is to get the current day as "Wednesday" not as an integer value, for example 1. My code is here.

#include <dos.h> #include <stdio.h> #include<conio.h> int main(void) { struct date d; getdate(&d); printf("The current year is: %d\n", d.da_year); printf("The current day is: %d\n", d.da_day); printf("The current month is: %d\n", d.da_mon); getch(); return 0; } 

Please help me find the current day like Sunday, Monday ......... Thank you

+6
c
source share
5 answers

Are you really writing for 16-bit DOS or just using some weird outdated tutorial?

strftime is available in any modern C library:

 #include <time.h> #include <stdio.h> int main(void) { char buffer[32]; struct tm *ts; size_t last; time_t timestamp = time(NULL); ts = localtime(&timestamp); last = strftime(buffer, 32, "%A", ts); buffer[last] = '\0'; printf("%s\n", buffer); return 0; } 

http://ideone.com/DYSyT

+9
source share

The headings you use are non-standard. Use functions from the standard:

 #include <time.h> struct tm *localtime_r(const time_t *timep, struct tm *result); 

After calling the function above, you can get a working day:

 tm->tm_wday 

Check out the tutorial / example .

Here is additional documentation with examples here .

As others have pointed out, you can use strftime to get the name of the day of the week when you have tm . Here is a good example here :

  #include <time.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char outstr[200]; time_t t; struct tm *tmp; t = time(NULL); tmp = localtime(&t); if (tmp == NULL) { perror("localtime"); exit(EXIT_FAILURE); } if (strftime(outstr, sizeof(outstr), "%A", tmp) == 0) { fprintf(stderr, "strftime returned 0"); exit(EXIT_FAILURE); } printf("Result string is \"%s\"\n", outstr); exit(EXIT_SUCCESS); } 
+4
source share

Alternatively, if you insist on using an outdated compiler, there is dosdate_t struct in <dos.h> :

 struct dosdate_t { unsigned char day; /* 1-31 */ unsigned char month; /* 1-12 */ unsigned short year; /* 1980-2099 */ unsigned char dayofweek; /* 0-6, 0=Sunday */ }; 

Fill it with

 void _dos_getdate(struct dosdate_t *date); 
+2
source share

Use struct tm Example

+1
source share

strftime is definitely the right way. Of course you could do

 char * weekday[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; char *day = weekday[d.da_day]; 

Of course, I assume that the value of getdate() is placed in the date structure, indexed at 0, and Sunday on the first day of the week. (I do not have a DOS window for testing.)

0
source share

All Articles