Nimmy said:
Apologies,
I mean by 'char', my date format is 01/04/2004 like dd/mm/yyyy (british
style),
how this will be transformed into struct tm mydate and I want to mydate to
get the above 01/04/2004...
I have seen time.h, then I decided to do as follow:
t.tm_mday = 01; /* Day of the Month */
t.tm_mon = 03; /* Month */ <FOR APRIL 03???>> Yes that's what it
says...
t.tm_year = (2004-1900)=104; /* Year - does not include century */ 104
+ 1900
/* I don't want the rest of them but it seems to be mandatory */
t.tm_wday = 4; /* Day of the week */
t.tm_yday = 0; /* Does not show in asctime */
t.tm_isdst = 0; /* Is Daylight SavTime; does not show in asctime */
Of course in this case, I will be getting the date, month and year in INT
format,
Still it is not exactly working what I want....
If you have code that doesn't produce the result you want:
a) Post the *complete* code.
b) Tell us *exactly* the result you want, and what you got instead.
Maybe you can use this:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
enum component {DAY = 1, MONTH, YEAR};
const int BAD_VALUE = -1;
int date_item(const char *s, char delim, enum component which)
{
long result = 0;
char *d = (char *)s;
char *end = NULL;
errno = 0;
switch(which)
{
case DAY:
result = strtol(d, &end, 10);
break;
case MONTH:
if(d = strchr(d, delim))
result = strtol(++d, &end, 10) - 1;
break;
case YEAR:
if (d = strchr(d, delim))
if(d = strchr(++d, delim))
result = strtol(++d, &end, 10);
break;
default:
end = d;
break;
}
return ((d == end) || (errno == ERANGE)) ? BAD_VALUE : (int)result;
}
struct tm* date(const char *s, char delim, unsigned int dst)
{
static struct tm dt = {0};
dt.tm_mday = date_item(s, delim, DAY);
dt.tm_mon = date_item(s, delim, MONTH);
dt.tm_year = date_item(s, delim, YEAR);
if(dt.tm_year != BAD_VALUE)
dt.tm_year -= 1900;
dt.tm_isdst = dst;
return dt.tm_mday != BAD_VALUE &&
dt.tm_mon != BAD_VALUE &&
dt.tm_year != BAD_VALUE
? &dt : NULL;
}
void show_date(struct tm *date)
{
if(mktime(date) != (time_t)-1)
{
printf("date->tm_mday == %d\n"
"date->tm_mon == %d\n"
"date->tm_year == %d\n",
date->tm_mday,
date->tm_mon,
date->tm_year);
putchar('\n');
printf("%s\n", asctime(date));
}
else
fprintf(stderr, "Data outside representable range\n");
}
int main(void)
{
FILE *input = NULL;
char buffer[100] = {0};
struct tm mydate = {0};
struct tm *dt = NULL;
input = fopen("mydate.txt", "r");
if(input == NULL)
{
fprintf(stderr, "Cannot open input\n");
return EXIT_FAILURE;
}
if(fgets(buffer, sizeof buffer, input) == NULL)
{
fprintf(stderr, "Error reading input or no input\n");
return EXIT_FAILURE;
}
fclose(input);
dt = date(buffer, '/', 0);
if(dt)
{
mydate = *dt;
show_date(&mydate);
}
else
fprintf(stderr, "Invalid data\n");
return 0;
}
Input file 'mydate.txt':
01/04/2004
Output:
date->tm_mday == 1
date->tm_mon == 3
date->tm_year == 104
Thu Apr 01 00:00:00 2004
-Mike