简体   繁体   中英

How do I portably add a large number of seconds to a time_t object?

Well I think the title sums it up. Suppose I have an object of type double which I obtained from running std::difftime on two time_t objects, and now I want to add the resulting number of seconds back to a time_t object. I don't mind losing fractions of seconds.

Note that the number of seconds might be large (ie. larger than the 60 seconds allowed in struct tm , but always lower than any integer primitive used to represent seconds on the respective machine / implementation, and never larger than the order of 1 year, although preferably I would not like this to be a restriction).

How would I go about doing this portably (ie. as per C standard)?

I am hoping not to have to divide into months, days, hours, minutes etc. and add them manually to struct tm object. Surely there's a better way!?

You are allowed to perform arithmetic with time_t values.

You can set up two struct tm objects one second apart (choose two times in the middle of a minute somewhere, where leap seconds are not allowed to occur, and at a local time where DST does not change), and call mktime() on them both to get two time_t values. Subtract the earlier of of those time_t values from the later, and this will give you a second in the same number of units in which time_t is measured on your system. Multiply this by the number of seconds you want to add, and add the result to your original time_t value. You can check the result by again calling difftime() on the original and new time_t values to see if the seconds difference was what you were expecting.

Note that even this isn't guaranteed to be portable, since technically, time_t isn't required to even have a resolution capable of distinguishing seconds, but it would be a pretty odd implementation that did not. Also, if time_t is a floating point value (which is unusual) and you wanted to add a really, really large number of seconds, you might run into floating point precision issues. In this case you could try adding hours for instance, instead of seconds, and set up your two struct tm structs accordingly. You might conceivably run into overflow issues with a large enough number of seconds, which you just can't do much about.

使用localtimetime_t值转换为struct tm ,它将时间分解为小时,分钟,秒等。适当调整秒数,然后使用mktime将结构中的值转换为time_t

Seems like a duplicate of this .

"The C date/time type time_t is implemented as the number of seconds since a certain date, so to add seconds to it you simply use normal arithmetic."

Even if it's in C, there should be no difference to C++ :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM