I was just about to write this myself, but I know this has to exist and I'm just managing to avoid all the Google keywords that would lead me right to it.
I would be looking for something like DDDMMMYYY where D, M, Y are the number of days, months, and years. So 00103000 would indicate a span of three months and one day, or 000000001 would indicate a span of one year. Ideally this format would also have a standard way to apply it that could take into consideration all of the pitfalls of timespan calculation like varying number of days in a month, leap years, etc.
I am not looking for a way to calculate a times开发者_运维百科pan between two known timestamps, as was asked here (Calculate relative time in C#), i'm looking for something like a specific string format I can store that would indicate a span of time to be used for determining a second unknown date from a known one.
Such as, using my fictitious format above: if I said "calculate what date would be 00103000 from September 15, 2009" would return "December 16, 2009", which is three months and one day after September 15th.
I would recommend looking at the ISO 8061 format for durations. It is not only easy to parse and apply to a given date, it is a well-known standard with a lot of resources available.
Determining the duration from two points in time is a bit trickier, but only because without input from the application, it is unclear whether 1-March to 1-June is 3 months or 92 days. Nonetheless, the format can express either equally well as well as, for example, 0.25 years.
The simplest and most common representation of this is a numeric: the number of seconds in the time span (which may or may not be fractional, depending on your needs). Many time libraries already represent time as seconds since the epoch, so this makes addition and subtraction of time trivial. The only major issue of concern is overflows (e.g. year 2038 bug).
精彩评论