Monday, October 5, 2015

c# - List all dates in a year that are a palindrome

I got a text message forward that today 5 October 2015, is a palindrome date. If you consider day first format (ddMMyyyy) then this would be 5102015.So I wanted to see if there are other dates in the year that are a palindrome.

In US the date format is always month first so for this program I am using the MMddyyyy format.So Sunday,May 10 2015 is a Palindrome.

using System;

namespace DatePalindrome

{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                DateTime oFirstDay = new DateTime(DateTime.Now.Year, 1, 1);
                DateTime oLastDay = new DateTime(DateTime.Now.Year, 12, 31);
                DateTime oDay = oFirstDay;
                while (oDay < oLastDay.AddDays(1))
                {
                    string sDay = oDay.ToString("MMddyyyy").StartsWith("0") ? oDay.ToString("MMddyyyy").Substring(1, 7) : oDay.ToString("MMddyyyy");
                    
                    char [] sArray = sDay.ToCharArray();
                    Array.Reverse(sArray);

                    if (sDay.Equals(new string(sArray)))

                        Console.WriteLine("Palindrome:{0} - Day:{1}",sDay,oDay.ToLongDateString());

                    oDay = oDay.AddDays(1);

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            Console.WriteLine("Done! Press any key to exit");
            Console.Read();
        }
    }
}















Now if you change the date format to MMddyy then all days from May 10 2015 to May 19 2015 are palindromes.

By making the code change for date format using this

string sDay = oDay.ToString("MMddyy").StartsWith("0") ? oDay.ToString("MMddyy").Substring(1, 5) : oDay.ToString("MMddyy");

We get



No comments: