Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

c++ - 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!?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use localtime to convert your time_t value into a struct tm, which holds the time broken down into hours, minutes, seconds, etc. Adjust the number of seconds appropriately, then use mktime to convert the values in the struct into a time_t.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...