Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a date string in c

Tags:

c

I am currently working on a c project and I am trying to get the date from the system and build that into a string.

I am very new to c so I'm currently learning as I go along but I cannot get this to work. Below is the code that I have

time_t now = time(NULL);
struct tm *t = localtime(&now);
char currentDate[13];
char day[3];
char month[3];
char year[5];
char hour[3];
char min[3];
sprintf(day, "%02d", t->tm_mday, sizeof(day));
sprintf(month, "%02d", t->tm_mon+1, sizeof(month));
sprintf(year, "%04d", t->tm_year + 1900, sizeof(year));
sprintf(hour, "%02d", t->tm_hour, sizeof(hour));
sprintf(min, "%02d", t->tm_min, sizeof(min));
strcat(currentDate, day);
strcat(currentDate, month);
strcat(currentDate, year);
strcat(currentDate, hour);
strcat(currentDate, min);
printf("Current Date: %s", currentDate);

When it does the printf it just prints a load of rubbish e.g.

Current Date: ÃÃx·Z¤ÿ·øÃéôÃÿ·^XÃé<95>úþ·^F^FÃ^P^_

What am I doing wrong.

like image 596
Boardy Avatar asked Nov 28 '22 09:11

Boardy


1 Answers

I would consider using ctime and/or strftime. It might get you what you want without messing too much with strings and time fields.

With strftime:

char text[100];
time_t now = time(NULL);
struct tm *t = localtime(&now);


strftime(text, sizeof(text)-1, "%d %m %Y %H:%M", t);
printf("Current Date: %s", text);
like image 167
smichak Avatar answered Dec 29 '22 07:12

smichak