Question

Let's say today is Monday. I want to find out what is the date for last Wednesday.

the logic I thought is 1) No of days difference from today to last saturday ( ie. 6 ) 2) Substract those many seconds from today

time_t now = time(0);
// determine the no of day differences i.e 6
time_t lastWeekTime = now - (86400 * 6);

This is not DST safe. Can some one tell me what I need to take care here.?

Thanks in advance

Was it helpful?

Solution

you could convert the time_t using localtime to a tm struct. This struct contains the days as values - you can just add/subtract. You just have to make sure that you change the month/year if necessary. After you changed it correctly, you can use mktime to convert it back.

Awkward but manageable. This way you don't need to know about DST but only about the number of days / month and month / year.

The better way would probably be to use Boost Date Time

OTHER TIPS

Dates don't have a notion of DST, that only applies to date-times, as you need a fractional part of the day to describe if you're before or after the switch. So Fri, 01 Jun 2012 is always Fri, 01 Jun 2012, regardless how many DST switches happen on that day, or before or after that day.

Your way is already the correct way, time() will give you the number of seconds since the (unix) Epoch and that scale does not observe daylight-saving switches, so lastWeekTime % 86400 will be exactly the same as now % 86400 (as per your computation actually). So if you only need the date just make sure not to print the time component, e.g. by subtracting now % 86400 from the result and using only UTC functions (gmtime()/timegm()).

If you want something like: Today is Monday and there's an appointment at 11:00. I want to move it exactly N days back in time. Then use your algorithm to go from Monday N days back and set the time part manually:

time_t now = time(NULL);
time_t then = now - 86400 * N;
time_t then_eleven = (then - then % 86400) + 11 * 3600;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top