# Create struct tm from user specified date

This is a discussion on Create struct tm from user specified date within the C Programming forums, part of the General Programming Boards category; I am trying to create a tm structure from a user specified date. How do I calculate tm_wday and tm_yday? ...

1. ## Create struct tm from user specified date

I am trying to create a tm structure from a user specified date. How do I calculate tm_wday and tm_yday? Below is an example.

Code:
```int main(void)
{
CreateTmStruct( 2009, 9, 30, 10, 7, 30 );
}

CreateTmStruct( int Year, int Month, int Day, int Hour, int Minutes, int Seconds )
{
struct tm tmStruct;

tmStruct.tm_sec = Seconds;
tmStruct.tm_min = Minutes;
tmStruct.tm_hour = Hour;
tmStruct.tm_mon = Month + 1;
tmStruct.tm_year = Year - 1900;
tmStruct.tm_wday = ?;
tmStruct.tm_yday = ?;
tmStruct.tm_isdst = 0;
}```

2. You can look here

For days since 1 January I believe you can calculate it. The only thing you have to take into account is if February has 28 or 29 days. An algorithm to determine that is:
Code:
```if (year % 4 == 0)
if (year % 100 == 0 && year % 400 != 0)
February has 29 days;```
For if this day is sunday, again you will have to caclulate. You can write what day it is today and have that as a reference date. Whenever you try to calculate the day, use this. So today is Wednesday, 30.9.2009. If I tell you what day is 2.9.1980 you should be able to calculate it.

So create two functions to do your job

3. They don't need to be initialized as the time() calls are smart enough to figure out the date with the information given. Why aren't you initializing the tm_mday member despite having its value "30". Initialize the struct tm members, then call mktime() and print all members of tmStruct to see if they match the provided input. You will automatically see the values for tm_wday and tm_yday filled in.

4. Thanks! I didn't realize that you could call mktime with an incomplete tm structure. I thought I would have to fill in every field.

5. Note that
Code:
`tmStruct.tm_mon = Month + 1;  /* incorrect */`
should be
Code:
`tmStruct.tm_mon = Month - 1;`

Popular pages Recent additions