Home > Software engineering >  I have a problem with format a date in C#
I have a problem with format a date in C#

Time:01-13

My pc time is in American form M/dd/yyyy h:mm tt so if I create a DateTime for example a DateTime.Now , that will be in a same form as my pc, but I need another format yyyy/MM/dd HH:mm:ss , but I cannot change the DateTime.Now to another format , because I only can do this if the result will be a string , but I need a DateTime typed variable.

I tried to fix this like this:

string formattedDate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
var time = DateTime.ParseExact(formattedDate, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(formattedDate);
Console.WriteLine(time);

but I got this output : Output

CodePudding user response:

A culture can be specified for a thread.

    System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("en-US");
    Console.WriteLine(DateTime.Now); // 1/13/2023 5:36:22 PM

    System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
    Console.WriteLine(DateTime.Now); // 01/13/2023 17:36:22
  • Related