user584018
user584018

Reputation: 11304

Machine date time format overrides code date time format

Below code:

 Console.WriteLine($"-b \"{DateTime.Now.AddHours(-2):M/d/yyyy hh:mm:ss}\"");

gives correct output for one machine (with no change in date/time format):

-b "6/19/2018 07:45:44"

but when I am running code on a different machine (where date/time format was changed), I'm not getting the expected output:

-b "6-19-2018 07:20:17"

What's wrong? do I need to add "Invariant Culture", etc?

Upvotes: 0

Views: 94

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25351

When you specify a date & time format, it is executed using the current thread culture. If you don't specify the thread culture, it is by default taken from the computer's culture. So when you run the same code on two different computers that have two different cultures, you may get two different date & time format.

In the format that you have, the / is a date separator and the : is a time separator. They are both substituted by the date and time separators of the thread culture. In your scenario, it seems that the date separator on the second machine is - and this is what you get.

To use / and : regardless of the machine's culture, surround them with single quotes like this:

Console.WriteLine($"-b \"{DateTime.Now.AddHours(-2):M'/'d'/'yyyy hh':'mm':'ss}\"");

Upvotes: 5

Related Questions