DateTime.ToString () does not work properly with a slash as a date separator

I want to convert the date time to "MM / dd / yyyy", and when I convert to this format, the date becomes like "xx-xx-xxxx". I wrote the code as

  var format = "MM/dd/yyyy HH:mm";
  DateTime dt = DateTime.Now;
  var dateString = dt.toString(format); // the value i am getting is 05-28-2014 12:47 but i require the 'dateString' value to be `05/28/2014 12:53`. 

What is the problem.

+4
source share
4 answers

Your real-time culture date separator seems to be -why you get it. You must specify InvariantCulture:

string dateString = dt.toString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);  

See: "/" Custom Format Specifier

"/" , , . DateTimeFormatInfo.DateSeparator .

- / \:

string dateString = dt.toString(@"MM\/dd\/yyyy HH\:mm");  

, , / " ", ( ) CultureInfo ( InvariantCulture) .

+16

. InvariantCulture :

var dateStringFormat= dt.toString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);  
+2

, DateTime.Now.ToString( "MM/dd/yyyy hh: mm ss tt" )

for more links. http://msdn.microsoft.com/en-us/library/system.datetime.aspx

0
source

Another way @TimSchmelter answers is by calling special characters /and :, therefore, they are not considered as day / time separators.

var dateString = dt.toString(@"MM\/dd\/yyyy HH\:mm");
0
source

Source: https://habr.com/ru/post/1542282/


All Articles