The basic problem here is that, the date separator depends on the culture setting of the system. Your application uses the culture configured on your system.
There are multiple ways already explained above to override this behaviour:
- Use
CultureInfo.InvariantCulture parameter as suggested by @David. - Escape the slash by specifying
\\/ as suggested by @BaRtEr. - Formatting the slash differently like
'/' as suggested by @Norbert.
Alternatively, you can change the configurations on your system to set the separator to slash instead of whatever is the default.
If you do not want to alter the system configurations, you can set the culture of your application as below:
public static void SetDefaultCulture(string culture) { CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(culture); Thread.CurrentThread.CurrentCulture = cultureInfo; Thread.CurrentThread.CurrentUICulture = cultureInfo; CultureInfo.DefaultThreadCurrentCulture = cultureInfo; CultureInfo.DefaultThreadCurrentUICulture = cultureInfo; Type type = typeof(CultureInfo); type.InvokeMember("s_userDefaultCulture", BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static, null, cultureInfo, new object[] { cultureInfo }); type.InvokeMember("s_userDefaultUICulture", BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static, null, cultureInfo, new object[] { cultureInfo }); }
Call this function at the start-up of your application like below:
SetDefaultCulture("en-US");
This will set the culture of your application to what you set while calling the function.
If this culture (one you set while calling the function) uses the slash as its date separator, below code will generate correct output:
DateTime dateTime = DateTime.Now; string dt = dateTime.ToString("MM/dd/yyyy"); string tm = dateTime.ToString("hh:mm:ss tt"); string dttm = dateTime.ToString("MM/dd/yyyy hh:mm:ss tt"); Console.WriteLine($"Date {dt}"); Console.WriteLine($"Time {tm}"); Console.WriteLine($"DateTime {dttm}");
Output:
Date 11/20/2025 Time 03:06:42 PM DateTime 11/20/2025 03:06:42 PM
string.Format("{0:M/d/yyyy H:mm:ss tt}", myDate)andstring.Format("{0:G}", myDate)