mktime and tm_isdst

前端 未结 3 1446
慢半拍i
慢半拍i 2020-12-30 04:16

I saw a lot of different views so thought of asking here.

I read man mktime:

 (A positive or zero value for tm_isdst causes mktime() to          


        
3条回答
  •  忘掉有多难
    2020-12-30 05:06

    I think that you should indeed use -1 for the tm_isdst field unless you have the information about the type of time you are dealing with.

    For example, in California we still have PST and PDT. If you are parsing a date and that timezone information is present, then you should set the tm_isdst accordingly. As Jim McNamara mentioned, these names are available in the tzname[] array after a call to tzset().

    For example, the following C++ code write PST/PDT:

    int main(int argc, char * argv [])
    {
        tzset();
        std::cerr << tzname[0] << "/" << tzname[1] << "\n";
    
        return 0;
    }
    

    The offset in the tzname[] array corresponds to the value of tm_isdst. (PST -- Pacific Standard Time, tm_isdst = 0, and PDT, Pacific Daylight Time, tm_isdst = 1.)

    If you do not have the timezone information in your input, then using -1 is the best choice. You run into a problem only when the date corresponds to the day and time when the change happens. As Rich Jahn explains, on Nov 4, 2012, he had a time change between standard and daylight time and around that time, gmtime() has to make a choice and it is not unlike the opposite of what you'd expect. That being said, it only happens for a total of 2 hours in a year and in the middle of the night. So unless you are working on a critical type of software where date is very important, it probably won't matter much.

    So, as a recap:

    • if you have the timezone attached to the date you want to convert, use that information to determine the value of tm_isdst (that being said, I'm not too sure how you handle that in case you have to support all timezones... the tzname[] array only gives you the user's current timezone.)
    • in all other cases, use -1

提交回复
热议问题