How to Find a current day in c language? - 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

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

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);
}

Alternatively, if you insist on using your outdated compiler, there's a 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 */
};
You fill it with:
void _dos_getdate(struct dosdate_t *date);

Use struct tm Example

strftime is certainly the right way to go. Of course you could do
char * weekday[] = { "Sunday", "Monday",
"Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
char *day = weekday[d.da_day];
I'm of course assuming that the value getdate() puts in the date struct is 0-indexed, with Sunday as the first day of the week. (I don't have a DOS box to test on.)

Related

Save the date of today in a string

I want to save the date of today in a string and have the following code with the following output:
Code:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("%02d-%02d", tm.tm_mday, tm.tm_mon + 1);
printf("\n");
}
Output (for today, November the 5th):
05-11
What is the easiest way to save 05-11 in a string?
You can use the standard strftime function (declared in "time.h"), which takes a variety of format specifiers (akin to those used in printf) to extract and format the various date and/or time fields of a struct tm.
In your case, you would use the %d and %m specifiers to get the (two-digit) day and month numbers:
#include <stdio.h>
#include <time.h>
int main()
{
char StrDate[8];
time_t t = time(NULL);
strftime(StrDate, sizeof(StrDate), "%d-%m", localtime(&t));
printf("%s\n", StrDate);
return 0;
}
You could even add the newline character to the StrDate buffer directly, by appending the %n format specifier.
I used sprintf() which worked fine for me
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
char str[80];
sprintf(str, "%02d-%02d", tm.tm_mday, tm.tm_mon + 1);
printf("%s", str);
printf("\n");
}

How can i get the current time in C with d/m/y format?

Which function can return current datetime with d/m/y format in C language?
EDIT:
here is my code:
#include <stdio.h>
#include <time.h>
int main()
{
time_t tmp_time;
struct tm * info;
time ( &tmp_time );
info = localtime ( &tmp_time );
printf ( "%s", asctime (info) );
}
this returns to me something like that Thu Jan 26 13:08:01 2017 and i would like to return 26/01/17 or 26/01/2017
Like this:
int main ()
{
time_t rawtime;
struct tm * currentTime;
time ( &rawtime );
currentTime = localtime ( &rawtime );
printf ( "%d/%d/%d", currentTime->tm_mday, currentTime->tm_mon+1, currentTime->tm_year+1900);
return 0;
}
Be careful, months are indexed since 0, and year is since 1900 in tm struct.
Perhaps like this:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(0);
if((time_t)-1 == t){
perror(0);
exit(1);
}
char buf[64];
struct tm tdata;
//I believe the 2 calls below should always succeed
//in this context
localtime_r(&t, &tdata);
strftime(buf, sizeof(buf), "%d/%m/%y", &tdata);
puts(buf);
}
The localtime(3) manpage says strftime is the recommended way to do it, and the strftime(3) manpage provides a similar example.
You can do it like this
#include <time.h>
#include <stdio.h>
int main(void)
{
time_t mytime = time(NULL);
struct tm date = *localtime(&mytime);
printf("now: %d/%d/%d\n", date.tm_mday,date.tm_mon + 1,date.tm_year +1900 );
return 0;
}
if you want to make it a function send the date as a parameter and return a int array holds day month and year

How to convert character string in microseconds to struct tm in C?

I have a string that contains microseconds since the epoch. How could I convert it to a time structure?
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main ()
{
struct tm tm;
char buffer [80];
char *str ="1435687921000000";
if(strptime (str, "%s", &tm) == NULL)
exit(EXIT_FAILURE);
if(strftime (buffer,80,"%Y-%m-%d",&tm) == 0)
exit(EXIT_FAILURE);
printf("%s\n", buffer);
return 0;
}
Portable solution (assuming 32+ bit int). The following does not assume anything about time_t.
Use mktime() which does not need to have fields limited to their primary range.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char buffer[80];
char *str = "1435687921000000";
// Set the epoch: assume Jan 1, 0:00:00 UTC.
struct tm tm = { 0 };
tm.tm_year = 1970 - 1900;
tm.tm_mday = 1;
// Adjust the second's field.
tm.tm_sec = atoll(str) / 1000000;
tm.tm_isdst = -1;
if (mktime(&tm) == -1)
exit(EXIT_FAILURE);
if (strftime(buffer, 80, "%Y-%m-%d", &tm) == 0)
exit(EXIT_FAILURE);
printf("%s\n", buffer);
return 0;
}
Edit: You could simply truncate the string, since struct tm does not store less than 1 second accuracy.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
struct tm now;
time_t secs;
char buffer [80];
char str[] ="1435687921000000";
int len = strlen(str);
if (len < 7)
return 1;
str[len-6] = 0; // divide by 1000000
secs = (time_t)atol(str);
now = *localtime(&secs);
strftime(buffer, 80, "%Y-%m-%d", &now);
printf("%s\n", buffer);
printf("%s\n", asctime(&now));
return 0;
}
Program output:
2015-06-30
Tue Jun 30 19:12:01 2015
You can convert the microseconds to seconds, and use localtime() like this
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main (void)
{
struct tm *tm;
char buffer[80];
char *str = "1435687921000000";
time_t ms = strtol(str, NULL, 10);
/* convert to seconds */
ms = (time_t) ms / 1E6;
tm = localtime(&ms);
if (strftime(buffer, 80, "%Y-%m-%d", tm) == 0)
return EXIT_FAILURE;
printf("%s\n", buffer);
return EXIT_SUCCESS;
}
Note that in the printed date, the microseconds are not present, so you can ignore that part.
Convert the string to a time_t, then use gmtime(3) or localtime(3).
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main () {
struct tm *tm;
char buffer [80];
char *str ="1435687921000000";
time_t t;
/* or strtoull */
t = (time_t)(atoll(str)/1000000);
tm = gmtime(&t);
strftime(buffer,80,"%Y-%m-%d",tm);
printf("%s\n", buffer);
return 0;
}

how to display datetime using C Programming

I have to display date and time separately using gettime() and getdate() in C programming language. The code I have written only displays date and time on same line. I want this code to be done using only core C not in a windows format.The editor I am using is Visual Studio 2008
Below I have post my code which only shows date time on a single line.
#include "stdafx.h"
#include <conio.h>
#include <stdio.h>
#include <time.h>
char *gettime();
int_main(int argc,_TCHAR* argv[])
{
printf("The time is %s\n",gettime());
getch();
return 0;
}
char *gettime()
{
time_t t;
tm b;
time(&t);
return ctime(&t);
}
You can use localtime/gmtime
struct tm * timeinfo;
timeinfo = localtime (&t);
And work with tm structure components as you need, also you can use strfrtime format function if you need only print date and time.
Main function is the same for all the different ways:
#include <stdio.h>
#include <time.h>
#include <string.h>
char * gettime();
char * getdate();
int main()
{
printf("The time is %s\n", gettime());
printf("The date is %s\n", getdate());
return 0;
}
One way you could do it is with manipulating the strings coming back from ctime() function. We know they are built in a similar way, the 1st 12 chars are week-day, month, month-day, then comes 8 chars of time, then finally the year. You could create functions like this:
char * gettime()
{
time_t t;
//use static so not to save the var in stack, but in the data/bss segment
//you can also make it a global scope, use dynamic memory allocation, or
//use other methods as to prevent it from being erased when the function returns.
static char * time_str;
time(&t);
time_str = ctime(&t) + 11;
time_str[9] = 0; //null-terminator, eol
return time_str;
}
char * getdate()
{
time_t t;
static char * date_str;
static char * year;
time(&t);
date_str = ctime(&t) + 4;
date_str[6] = 0;
year = date_str + 15;
year[5] = 0;
strcat(date_str, year);
return date_str;
}
The second way to do this is using localtime() function to create a tm-struct, and then extract what you need from it.
char * gettime()
{
time_t t;
struct tm *info;
static char time_str[10];
time(&t);
info = localtime(&t);
sprintf(time_str,"%d:%d:%d",(*info).tm_hour, (*info).tm_min, (*info).tm_sec);
return time_str;
}
char * getdate()
{
time_t t;
struct tm *info;
static char date_str[12];
time(&t);
info = localtime(&t);
sprintf(date_str,"%d/%d/%d",(*info).tm_mday, (*info).tm_mon+1, (*info).tm_year+1900);
return date_str;
}
You can make it a bit more clean using the strftime() function:
char * gettime()
{
time_t t;
struct tm *info;
static char time_str[10];
time(&t);
info = localtime(&t);
strftime(time_str, 10, "%S:%M:%H",info);
return time_str;
}
char * getdate()
{
time_t t;
struct tm *info;
static char date_str[12];
time(&t);
info = localtime(&t);
strftime(date_str, 12, "%d:%m:%Y",info);
return date_str;
}

Formatting struct timespec

How to format struct timespec to string? This structure is returned e.g. by clock_gettime() on Linux gcc:
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
One way to format it is:
printf("%lld.%.9ld", (long long)ts.tv_sec, ts.tv_nsec);
I wanted to ask the same question. Here is my current solution to obtain a string like this: 2013-02-07 09:24:40.749355372
I am not sure if there is a more straight forward solution than this, but at least the string format is freely configurable with this approach.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define NANO 1000000000L
// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
int ret;
struct tm t;
tzset();
if (localtime_r(&(ts->tv_sec), &t) == NULL)
return 1;
ret = strftime(buf, len, "%F %T", &t);
if (ret == 0)
return 2;
len -= ret - 1;
ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
if (ret >= len)
return 3;
return 0;
}
int main(int argc, char **argv) {
clockid_t clk_id = CLOCK_REALTIME;
const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
char timestr[TIME_FMT];
struct timespec ts, res;
clock_getres(clk_id, &res);
clock_gettime(clk_id, &ts);
if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
printf("timespec2str failed!\n");
return EXIT_FAILURE;
} else {
unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
return EXIT_SUCCESS;
}
}
output:
gcc mwe.c -lrt
$ ./a.out
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501
The following will return an ISO8601 and RFC3339-compliant UTC timestamp, including nanoseconds.
It uses strftime(), which works with struct timespec just as well as with struct timeval because all it cares about is the number of seconds, which both provide. Nanoseconds are then appended (careful to pad with zeros!) as well as the UTC suffix 'Z'.
Example output: 2021-01-19T04:50:01.435561072Z
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int utc_system_timestamp(char[]);
int main(void) {
char buf[31];
utc_system_timestamp(buf);
printf("%s\n", buf);
}
// Allocate exactly 31 bytes for buf
int utc_system_timestamp(char buf[]) {
const int bufsize = 31;
const int tmpsize = 21;
struct timespec now;
struct tm tm;
int retval = clock_gettime(CLOCK_REALTIME, &now);
gmtime_r(&now.tv_sec, &tm);
strftime(buf, tmpsize, "%Y-%m-%dT%H:%M:%S.", &tm);
sprintf(buf + tmpsize -1, "%09luZ", now.tv_nsec);
return retval;
}
GCC command line example (note the -lrt):
gcc foo.c -o foo -lrt
You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.
You could use a std::stringstream. You can stream anything into it:
std::stringstream stream;
stream << 5.7;
stream << foo.bar;
std::string s = stream.str();
That should be a quite general approach. (Works only for C++, but you asked the question for this language too.)

Resources