From 6d6cca7830ed931198cd2df77bafbdd81038171a Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Mon, 31 Aug 2009 22:40:57 +0000 Subject: Added a getDaysInMonth function, it'll live in util.{cpp,h} until I create an actual Date class. --- src/tests/daysinmonth.cpp | 16 ++++++++++++++++ src/util.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ src/util.h | 6 ++++++ 3 files changed, 62 insertions(+) create mode 100644 src/tests/daysinmonth.cpp diff --git a/src/tests/daysinmonth.cpp b/src/tests/daysinmonth.cpp new file mode 100644 index 0000000..9888844 --- /dev/null +++ b/src/tests/daysinmonth.cpp @@ -0,0 +1,16 @@ +#include "bu/sio.h" +#include "bu/util.h" + +using namespace Bu; + +int main() +{ + for( int j = 0; j < 12; j++ ) + { + sio << "2012-" << j << " = " + << getDaysInMonth( j, 2012 ) << sio.nl; + } + + return 0; +} + diff --git a/src/util.cpp b/src/util.cpp index 111574c..3ca711d 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -1 +1,41 @@ #include "bu/util.h" + +int Bu::getDaysInMonth( int iMonth, int iYear ) +{ + if( iMonth > 11 ) + { + iYear += iMonth/12; + iMonth = iMonth%12; + } + switch( iMonth ) + { + case 0: + case 2: + case 4: + case 6: + case 7: + case 9: + case 11: + return 31; + break; + + case 3: + case 5: + case 8: + case 10: + return 30; + break; + + case 1: + if( iYear%400 == 0 ) + return 29; + if( iYear%100 == 0 ) + return 28; + if( iYear%4 == 0 ) + return 29; + return 28; + break; + } + +} + diff --git a/src/util.h b/src/util.h index 0c2f0eb..c284880 100644 --- a/src/util.h +++ b/src/util.h @@ -167,6 +167,12 @@ namespace Bu return *a > *b; } }; + + /** + * Get the number of days in the month in the gregorian calendar, taking + * leap years into account. + */ + int getDaysInMonth( int iMonth, int iYear ); }; #endif -- cgit v1.2.3