How to Find palindrome dates in C# – Programming, Pseudocode Example, C# Programming Example
C# Windows Form

How to Find palindrome dates in C#

A palindrome date is a date that, in numeric format, reads the same forward and backward. For example, 12/1/21.

To find the most dates, you can consider all formats including two-digit days and four-digit years, and you can ignore the separator characters. For example, 12/02/2021 is a palindrome because 12022021 is the same forward and backward.

Obviously this depends on whether you use the m/d/y, d/m/y, or y/m/d format.

December 2021 had a whopping 11 palindrome dates! (In the m/d/y format.)

When you click the Go button, the program uses the following code to search for palindrome dates.

This code clears the program’s list box and then defines valid date formats depending on whether the m/d/y, d/m/y, or y/m/d radio button is selected.

There are a few other formats that you could use, but they seemed a bit arbitrary. For example, you could use a one-digit month and a two-digit day. I decided that month and day should be either both one-digit or both two-digit.

The program then parses the start date and the number of dates it should examine, and enters a loop.

Inside the loop, the program creates a new list of strings to hold any palindromes that it finds for this date. It then loops through the date formats.

The code uses each format to convert the date into a string. If that date string is not already in the palindromes list and if the string is the same as its reverse, then the program adds it to the list box and the palindromes list.

The program uses the palindromes list to avoid adding the same date to the list box multiple times if the date has a month or day number greater than 9. For example, the two-digit month and day numbers for the date 12/11/21 are the same as the one-digit versions, so the formats Mdyy, MMdyy, Mddyy, and MMddyy all produce the string 121121.

After it has finished looping through the formats, the code adds one day to the date it is considering so it can continue looking at dates.

The following code shows the Reverse helper method.

This method takes a string, converts it into a character array, reverses the array, converts the result (which is a weird LINQ enumerable) into an array, and uses it to initialize a new string. The result is the original string reversed.

You could use this statement directly in the button’s Click event handler, but I thought it would clutter that code a bit.

You could also convert this into a string extension method (in fact I did that originally), but that seems like overkill for this simple example. If you need to reverse strings frequently, you might want to do that.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.