Home > OS >  convert date string to date time c#
convert date string to date time c#

Time:10-29

I have this confusion of converting 23/09/21 or 09/23/21 to a valid datetime

23/09/21 refers to development environment , 09/23/21 refers to customer deploy environment

string _tmpCreatedDate = ((SAPbouiCOM.EditText)b1MatrixUser.Columns.Item("Col_8").Cells.Item(i   1).Specific).Value;

hence becomes string _tmpCreatedDate = "23/09/21";

DateTime _swapCreatedDate = Convert.ToDateTime(_tmpCreatedDate);

above code will output string was not recognized as a valid DateTime.

tried _tmpCreatedDate = Convert.ChangeType(_tmpCreatedDate, typeof(DateTime)).ToString();

as well, same convert issue, as the input string is dynamic dd/MM/yy or MM/dd/yy how to handle this in correct way?

CodePudding user response:

I think you can simply use DateTime.ParseExact

  DateTime dt = DateTime.ParseExact(_tmpCreatedDate , "MM/dd/yyyy",CultureInfo.InvariantCulture);

Read more over here CultureInfo.InvariantCulture Property and DateTime.ParseExact

CodePudding user response:

Added as comment, but to OP request, I am adding an answer:

You could specify date format in config in your application or detect in code, at app startup if it's development mode, then you can save appropriate format in some global variable.

One of ideas, if you're using dependency injection, would be to define some date provider service or even you could try specifying own IFormatProvider or something like that, and then using it in parsing methods of DateTime.

  • Related