How To: Convert Day Number to Month and Day

I needed to convert the day number, that is, what day it is between 1 and 365, into a month and day without using Calendar / DateTime classes and such today, so I knocked up a few simple functions that work assuming it’s not a leap year (i.e. that February has 28 days).

Here they are if they’re of any use to you:

A touch cheap, but it gets the job done.

4 thoughts on “How To: Convert Day Number to Month and Day”

    1. Haha, that’s a very clever way of doing it. Thanks for pointing this out!

      Also, thanks for the implementation link – very well done.

      Update: In case the pastebin link expires or such, here is Mneumonic Carrier’s provided reference implementation:

      1. You’re welcome! I thought it would be better posting my code in pastebin rather than the comments section here, as I wasn’t sure if code would be formatted correctly here.

        Whenever working with dates, the first step is to convert that date into a “date number”. This isn’t actually that difficult, but most people don’t realize that a leap year is: “…every four years, except if the year is divisible by 100, but even then it’s still a leap year if it’s divisible by 400…”.

        A clear understanding of the problem domain is essential (and sometimes it requires a little effort (i.e. reading) to understand the problem domain).

        My CalcDateFromDayNum() method could be implemented in many different ways. I’m used a template function because it’s something I’m used to using for returning more complex data structures from a method (in this case, a string vector). However, a neater way to achieve this would be to pass an iterator to the string vector container instead, like so:

        And then call it like this:

        The advantage of doing it this way is it’s more versatile, as all containers have iterators (i.e. the previous implementation would only work with containers that support the push_back() method).

        Of course, another way would be to simply return a stringvec (string vector), just like CalcDayAndMonth does:

        Of course, you could always use a properly defined struct or class to hold the date type:

        In which case your CalcDateFromDayNum() becomes:

        and CalcDayAndMonth() becomes:

        And inside your main() you do:

        The latter (with the TDate struct) is problem much easier to read and understand (instead of relying on a stringvec).

        Here’s the complete implementation using the TDate struct:

        As an added bonus, it’s a trivial matter to find the “Day of Week”:

        But now I’m just rambling…

        1. Wow! A very comprehensive coverage of the matter – and orders of magnitude more thought than I’d put into it!

          Outstanding work. I salute you, sir! =D

Leave a Reply

Your email address will not be published.