Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find a current day in c language?

Tags:

c

I am able to get the current date but the output is like 9/1/2010,but my requirement is to get the current day like"Wednesday" not in form of integer value like 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 to find the current day as Sunday,Monday......... Thanks

like image 632
PrateekSaluja Avatar asked Sep 01 '10 14:09

PrateekSaluja


2 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

like image 65
Cat Plus Plus Avatar answered Oct 05 '22 21:10

Cat Plus Plus


The headers you are using are nonstandard. Use functions from the standard:

#include <time.h>

struct tm *localtime_r(const time_t *timep, struct tm *result);

After you call the function above, you can get the weekday from:

tm->tm_wday

Check out this tutorial/example.

There's more documentation with examples here.

As others have pointed out, you can use strftime to get the weekday name once you have a tm. There's 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);
   }
like image 35
bstpierre Avatar answered Oct 05 '22 22:10

bstpierre