You can use Regex.Replace to change the format of a date string. For example if your input string is YYYY/MM/DD but you need to change it to YYYY-MM-DD, you can use this small 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 are unreadable as usual, but the trick here lies in the way the year, month and day parts are grabbed and stored in “variables” to be used in the replacement part of the Regex.Replace:
- Pattern: (?\\d{2,4}) grabs 2-4 digits and places them in a variable called “year”. The same goes for month and day.
- Replacement: ${year} places the value grabbed from the input and places it into the output of the replace function.
With this in mind we can create lots of different search/replace patters:
- Input: DD/MM/YYYY Output: 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-DD Output: MM/DD/YYYY
Patern: \\b(??<year>\\d{2,4})-(??<month>\\d{1,2})-(??<day>\\d{1,2})\\b
Replacement: ${month}/${day}/${year}
Would you like to change multiple dates from your input? 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; } }
Or how about changing dates from within an XML document?
<item> <start_date>2019/06/11</start_date> <expiration_date>2019/06/17</g:expiration_date> </item>
Add the < > to the pattern and replacement variables:
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; } }
MORE TO READ:
-
Regular Expression Example: Changing Date Formats from docs.microsoft.com
-
Regex.Replace Method from docs.microsoft.com
-
.NET Exceptions – RegexMatchTimeoutException by Andrew Powell-Morse