How to Change date format using .NET Regular Expressions

By FoxLearn 1/14/2025 8:43:47 AM   96
To change a date format using .NET Regular Expressions, you follow these steps.

You can use Regex.Replace to change the format of a date string.

For instance, if your input string is in the format YYYY/MM/DD but you need to change it to YYYY-MM-DD, you can use the following method:

public static string ReformatDate(string input) 
{
   try {
      return Regex.Replace(input, 
            "\\b(?<year>\\d{2,4})/(?<month>\\d{1,2})/(?<day>\\d{1,2})\\b",
            "${year}-${month}-${day}", 
            RegexOptions.IgnoreCase,
            TimeSpan.FromMilliseconds(1000));
   }         
   catch (RegexMatchTimeoutException) {
      return input;
   }
}

Regular expressions can be difficult to read, but the key here is how the year, month, and day components are captured and stored in named groups (variables) for use in the replacement part of the Regex.Replace function:

  • Pattern: (?\\d{2,4}) captures 2-4 digits and stores them in a variable called "year". The same applies for month and day.
  • Replacement: ${year} inserts the value captured from the input into the output during the replacement.

 

This allows us to create various search/replace patterns:

  • Input: DD/MM/YYYYOutput: YYYY-MM-DD

    • Pattern: \b(?<day>\d{1,2})/(?<month>\d{1,2})/(?<year>\d{2,4})\b
    • Replacement: ${year}-${month}-${day}
  • Input: YYYY-MM-DDOutput: MM/DD/YYYY

    • Pattern: \b(?<year>\d{2,4})-(?<month>\d{1,2})-(?<day>\d{1,2})\b
    • Replacement: ${month}/${day}/${year}

If you want to change multiple dates in your input, you can add RegexOptions.Multiline to the options:

public static string ReformatDate(string input) 
{
   try 
   {
      return Regex.Replace(input, 
            "\\b(?<year>\\d{2,4})/(?<month>\\d{1,2})/(?<day>\\d{1,2})\\b",
            "${year}-${month}-${day}", 
            RegexOptions.Multiline | RegexOptions.IgnoreCase,
            TimeSpan.FromMilliseconds(1000));
   }         
   catch (RegexMatchTimeoutException) 
   {
      return input;
   }
}

To change dates within an XML document

For example:

<item>
 <startdate>2025/01/14</start_date>
 <expirationdate>2025/01/20</g:expiration_date>
</item>

You can add the < > symbols to your pattern and replacement:

public static string ReformatDate(string input) 
{
   try 
   {
      return Regex.Replace(input, 
            ">\\b(?<year>\\d{2,4})/(?<month>\\d{1,2})/(?<day>\\d{1,2})\\b<", 
            ">${year}-${month}-${day}<", 
            RegexOptions.Multiline | RegexOptions.IgnoreCase,
            TimeSpan.FromMilliseconds(1000));
   }         
   catch (RegexMatchTimeoutException) 
   {
      return input;
   }
}

If you're dealing with multiple formats or more complex date transformations, you may need to adjust the regular expression