-1

I have 5 time unit, namely: Day, Week, Month, Quarter, Year.

How do I write a function to calculate the number of periods between 2 time units? For example,

number of Days in a Month --> should be either 28, 29, 30 or 31 days depend on the month.

number of Days in a Year --> should be either 365 or 366 days depends on if the year is a leap year.

number of Months in a Year --> 12 months.

number of Quarter in a Year --> 4 Quarters.

number of Weeks in a month --> Maybe 4 or 5 weeks.

etc..

I know I can do it using brute-force method. However, is there any better way to do it?

Thanks in advance!

spflee
  • 151
  • 7
  • Some months have 28 or 29 days. [Or 19, if you are really unlucky](http://www.timeanddate.com/calendar/monthly.html?year=1752&month=9&country=1) – Bo Persson Aug 01 '12 at 13:38
  • So you removed the "C++" tag, and from your comment below it is clear that you are using something uncommon, but you don't want to tell us what. That makes it really hard to give you a helpful answer. It would be interesting what your "uncommon" language does provide. For example, does it provide date/time functions similar to the ANSI C libraries? Does it provide integer and/or floating point operations? Is it a "high level language" or some kind of assembler dialect? – Doc Brown Aug 01 '12 at 14:15

2 Answers2

2

Date, time and calendar calculations are hard.

They are also older than the dawn of time itself, so why reinvent the wheel? If C++ is your choice language, why not look at Boost Date_Time ?

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • 1
    Somehow I'm skeptical that calculating the time is older than time itself :P – Chaosed0 Aug 01 '12 at 13:34
  • Hi Dirk, Sorry that the language that I used is not C++. It is not a common programming language found in market. Anyway, Thanks! – spflee Aug 01 '12 at 13:42
0

Start with this function to calculate the difference in seconds between two date/time values.

Now, all you have to add is a conversion from your input parameters (two points in time in one of your time units) to the types used in that function above, and another conversion from "seconds" to the time unit you want for the result of your calculation.

Community
  • 1
  • 1
Doc Brown
  • 19,739
  • 7
  • 52
  • 88