Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Apostrophe ' ' in custom format for date

Tags:

c#

datetime

In docs for Microsoft C# says

To change the time separator for a particular date and time string, specify the separator character within a literal string delimiter. For example, the custom format string hh'_'dd'_'ss produces a result string in which "_" (an underscore) is always used as the time separator.

In my code i tried to use separator for Date with both ways with and without Apostrophe as shown but the Result were the same for both outputs !

With Apostrophe

var __Date = new DateTime(1998, 07, 8, 07, 5, 1).ToString("yyyy'-'MM'-'dd hh':'mm':'ss");

the output as : 1998-07-08 07:05:01

Without Apostrophe

var _Date = new DateTime(1998,07,8,07,5,1).ToString("yyyy-MM-dd hh:mm:ss");

the output as : 1998-07-08 07:05:01

Could some one really tell me what is the purpose for Apostrophe in the separator for date in docs ?

like image 468
Ammar Bamhdi Avatar asked Jul 23 '18 19:07

Ammar Bamhdi


1 Answers

The : custom format specifier has special meaning as:

replace me with the current culture or supplied culture time separator.

That means, if you use a culture that doesn't have : as a TimeSeparator, that : replaced with your current culture's TimeSeparator in the output. Those apostrophes are there to escape your time separator no matter your current culture time separator is : or not.

Your first code generates : as an output no matter what your current culture's TimeSeparator since you escape them.

Your second code generates : as an output only if your current culture has : as a TimeSeparator.

For example, ml-IN culture does have . as a TimeSeparator (at least in .net framework 4.6.1 and be aware, those separators might change over .net framework or os version). If you change your CurrentCulture to ml-IN, you will get 1998-07-08 07.05.01 as an output.

These rules are the same for the / custom format specifier as well as a DateSeparator.

like image 196
Soner Gönül Avatar answered Oct 09 '22 05:10

Soner Gönül