Reputation: 213
I am using strptime to parse a user date input string with the following formatters: %F %T %z
for the format YYYY-MM-DD HH:MM:SS +-UTC offset
. I would like to add an option so that the user can specify whether or not Daylight Savings Time is in effect (0 or 1), and set tm_isdst
accordingly. This is important because I later use the user's input to convert into UTC epoch time, and the local time zone offset depends on DST. I store the user's tm_gmtoff
before converting, since mktime
adapts to local time, and then add or subtract based on their offset input.
Is there any formatter I can use within strptime
to toggle DST directly, or will I have to figure out another solution?
Upvotes: 1
Views: 2189
Reputation: 213
While the answers given told me a lot about strptime and UTC offset, my question was whether there is a way to set DST through strptime, as my concern was over mktime() using the local time of the system. Unfortunately, there is not a formatter, so I rewrote my code to manually convert to UTC based on the hour offset provided and then convert to an epoch timestamp using gmtime.
Upvotes: 1
Reputation: 154255
As @Jonathan Leffler points out, the usual way of looking at the UTC offset in YYYY-MM-DD HH:MM:SS +-UTC offset
is the offset from UTC for that date & time, not the standard offset for the user's timezone. Thus there is no info about timezone name and DST rules, just an offset.
To convert that input to time_t (the UTC epoch), if strptime()
understands %F %T %z
, after strptime()
call, call gmtime()
. No need to consider DST. If your strptime()
does not understands %z
, parse the offset yourself and subtract the minute result from the tm_min field of the strptime()
call, then call gmtime()
.
On the other hand, your application may be attempting to take a different approach in prompting the user to enter the date, time and standard time offset for the user's timezone. In this case, knowing if DST is in effect for that date & time is needed. With various strptime()
out there, one may have a % for a DST flag, but I do not see one, you likely need to do work. Convert as above and, if DST is set, subtract the usual 3600 seconds. *3
** The behavior of strptime()
might be affected by the LC_CTYPE, LC_TIME, and LC_TOD categories of the current locale.
If %F
does not work, try %Y-%m-%d
.
*3 The difference in offset from standard time to daylight time is usually 3600 seconds. I know of no present day exceptions. Historical exceptions exist.
Upvotes: 0