简体   繁体   中英

convert date string to date time c#

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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM