How to: Change Date Formats

Microsoft Silverlight will reach end of support after October 2021. Learn more.

The following example uses the Regex.Replace method to replace dates of the form mm/dd/yy with dates of the form dd-mm-yy. The Replace(String, String, String) function is one of several static functions that enable you to use regular expression operations without creating an explicit regular expression object. This example demonstrates the use of named backreferences within the replacement pattern for Replace(String, String, String). Here, the replacement expression ${day} inserts the substring captured by the group (?<day>…).

Example

Imports System.Globalization
Imports System.Text.RegularExpressions

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim dateString As String = Date.Today.ToString("d", _
                                           DateTimeFormatInfo.InvariantInfo)
      Dim resultString As String = MDYToDMY(dateString)
      outputBlock.Text += String.Format("Converted {0} to {1}.", dateString, resultString) & vbCrLf
   End Sub

   Function MDYToDMY(ByVal input As String) As String
      Return Regex.Replace(input, _
          "\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b", _
          "${day}-${month}-${year}")
   End Function
End Module
' The example displays the following output if run on 8/21/2007:
'      Converted 08/21/2007 to 21-08-2007.
using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      string dateString = DateTime.Today.ToString("d",
                                        DateTimeFormatInfo.InvariantInfo);
      string resultString = MDYToDMY(dateString);
      outputBlock.Text += String.Format("Converted {0} to {1}.", dateString, resultString) + "\n";
   }

   static string MDYToDMY(string input)
   {
      return Regex.Replace(input,
          "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
          "${day}-${month}-${year}");
   }
}