0

My application provides an export function to create a text file that can be imported to another software. The export file, has to look exactly like the other software has specified, in terms of formatting etc.

There is a date field that has to be in the format "yyyy/MM/dd HH:mm:ss".

The following code is used to write the line containing the date:

            txt += "       Started at: " + System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")+"\n";

Now when i look at the created text file, the date is in the wrong format, its formatted as following:

yyyy.mm.dd HH:mm:ss

I tried to swap out some characters to see if its a general issue, but it seems related to /, when i replace the / by _ or - it works as expected, even if only switch one of the three /, only the / gets wrongly converted into a point.

What could be the issue here?

snx
  • 33
  • 6
  • It is issue of culture, try this out var cult = CultureInfo.CreateSpecificCulture("en-US"); var txt = " Started at: " + System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", cult) + "\n"; – Sameh May 13 '21 at 14:05

2 Answers2

3

/ in custom datetime formatting refers to the "current system date separator", not the literal /.

To use a literal /, append it in quotes or double quotes, e.g:

System.DateTime.Now.ToString("yyyy'/'MM'/'dd HH:mm:ss")

Here's the documentation about it: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#dateSeparator

PS: notice the same happens with : for time

Jcl
  • 27,696
  • 5
  • 61
  • 92
0

Just like "mm" is replace by the month, the "/" is replaced by the "date specifier". See https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#dateSeparator

bwakabats
  • 603
  • 3
  • 9