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;
}
Related
I am using difftime() to try to subtract two dates. But consider, as in this example, I'm getting incorrect result. Here's the code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
const struct tm* stringToDate(const char *iDateStr)
{
struct tm *tm = (struct tm*)malloc(sizeof(struct tm));
memset(tm, 0, sizeof(struct tm));
sscanf_s(iDateStr, "%d-%d-%d", &tm->tm_mday, &tm->tm_mon, &tm->tm_year);
tm->tm_year -= 1900;
return tm;
}
const int stringDateDiffDays(const char *isDateTime1, const char *isDateTime2)
{
const struct tm *d1 = stringToDate(isDateTime1);
const struct tm *d2 = stringToDate(isDateTime2);
int diff = 0;
double diffSecs = 0;
// Seconds since start of epoch
diffSecs = difftime(mktime((struct tm*)d1), mktime((struct tm*)d2));
free((void *)d1);
free((void *)d2);
diff = (int)(diffSecs/(3600*24));
return diff;
}
int main(void)
{
char date1[] = "16-11-2017";
char date2[] = "16-12-2017";
printf("Date 1: %10s\n", date1);
printf("Date 2: %10s\n", date2);
printf("\nDifference : %d", stringDateDiffDays(date2, date1));
return 0;
}
What has happened? Is stringToDate() responsible for this, because of maybe the memset()? I am using Visual Studio 2012 to compile this code. How could I correctly implement these functions?
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
I want to get current time (without a current date) in C. The main problem is when I want to do it with functions. When I dont use them, evertyhing is just fine. Can anybody tell me, why my code shows only an hour? (take a look at the attached image). Thanks in advance.
#include <stdio.h>
#include <time.h>
#include <string.h>
char* get_time_string()
{
struct tm *tm;
time_t t;
char *str_time = (char *) malloc(100*sizeof(char));
t = time(NULL);
tm = localtime(&t);
strftime(str_time, sizeof(str_time), "%H:%M:%S", tm);
return str_time;
}
int main(int argc, char **argv)
{
char *t = get_time_string();
printf("%s\n", t);
return 0;
}
sizeof(str_time) gives you the size of char*. You want the size of the buffer str_time points to instead. Try
strftime(str_time, 100, "%H:%M:%S", tm);
// ^ size of buffer allocated for str_time
Other minor points - you should include <stdlib.h> to pick up a definition of malloc and should free(t) after printing its content in main.
The sizeof operator returns the length of the variable str_time which is a pointer to char. It doesn't returns the length of your dynamic array.
Replace sizeof(str_time) by 100 and it will go fine.
try this...
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
Use This Concept Getting System Time and Updating it. I have used this in my project many years before. you can change it as per your requirements.
updtime() /* FUNCTION FOR UPDATION OF TIME */
{
struct time tt;
char str[3];
gettime(&tt);
itoa(tt.ti_hour,str,10);
setfillstyle(1,7);
bar(getmaxx()-70,getmaxy()-18,getmaxx()-30,getmaxy()-10);
setcolor(0);
outtextxy(getmaxx()-70,getmaxy()-18,str);
outtextxy(getmaxx()-55,getmaxy()-18,":");
itoa(tt.ti_min,str,10);
outtextxy(getmaxx()-45,getmaxy()-18,str);
return(0);
}
The previous function will update time whenever you will call it like
and this will give you time
int temp;
struct time tt;
gettime(&tt); /*Get current time*/
temp = tt.ti_min;
If you want to update time the you can use the following code.
gettime(&tt);
if(tt.ti_min != temp) /*Check for any time update */
{
temp = tt.ti_min;
updtime();
}
This is complex code but if you understand it then it will solve your all problems.
Enjoy :)
In getting the time, you can try this one:
#include <stdio.h>
int main(void)
{
printf("Time: %s\n", __TIME__);
return 0;
}
Result:
Time: 10:49:49
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(×tamp);
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.)
I have a date string format say like "2010-03-01" and I want to get the "tm_wday" equivalent of it say like Monday, Tuesday ...
Could someone give me a hint on how to achieve this in c?
Check the strptime() function:
char *strptime(const char *s, const char *format, struct tm *tm);
The strptime() function is the converse function to strftime(3) and converts the
character string pointed to by s to values which are stored in the tm structure
pointed to by tm, using the format specified by format.
Use mktime() to calculate the weekday.
#include <memory.h>
#include <stdio.h>
#include <time.h>
int main(void) {
const char *p = "2010-03-01";
struct tm t;
memset(&t, 0, sizeof t); // set all fields to 0
if (3 != sscanf(p,"%d-%d-%d", &t.tm_year, &t.tm_mon, &t.tm_mday)) {
; // handle error;
}
// Adjust to struct tm references
t.tm_year -= 1900;
t.tm_mon--;
// Calling mktime will set the value of tm_wday
if (mktime(&t) < 0) {
; // handle error;
}
printf("DOW(%s):%d (0=Sunday, 1=Monday, ...)\n", p, t.tm_wday);
// DOW(2010-03-01):1 (0=Sunday, 1=Monday, ...)
return 0;
}