I need to convert below 2 string formats to DateTime
"M/dd/yyyy hh:mm:ss tt", "MM-dd-yyyy hh:mm"
// CultureInfo enUS = new CultureInfo("en-IN");
CultureInfo enUS = new CultureInfo("en-GB");
i) dt = "07/30/2022 5:30:39 PM";
ii) // dt = "7/30/2022 5:30:39 PM";
iii) // var dt = "11-07-2022 09:22";
DateTime dateValue;
string[] formatStrings = { "M/dd/yyyy hh:mm:ss tt", "MM/dd/yyyy hh:mm:ss tt", "MM-dd-yyyy hh:mm" };
if (DateTime.TryParseExact(dt, formatStrings, enUS, DateTimeStyles.None, out dateValue))
return dateValue;
The above code convert only '-' date fornat not '/' format . Is it possible to convert to '/' date format
EXPECTED OUTPUT: 30/07/2022 for i & ii
07/11/2022 for iii
CodePudding user response:
The input you have is:
"07/30/2022 5:30:39 PM"
The pattern you're trying to match that against is:
"M/dd/yyyy hh:mm:ss tt"
Note that your input has two digits for the month, but you've told it not to match a leading zero; and that you hour doesn't start with a leading zero but your pattern says it should.
Your pattern should be this:
"MM/dd/yyyy h:mm:ss tt"
If you try that you'll see it works.
Here is working code for all of your inputs:
CultureInfo enUS = new("en-US");
string[] dts =
{
"07/30/2022 5:30:39 PM",
"7/30/2022 5:30:39 PM",
"11-07-2022 09:22",
};
string[] formatStrings =
{
"MM/dd/yyyy h:mm:ss tt",
"M/dd/yyyy h:mm:ss tt",
"MM-dd-yyyy hh:mm"
};
IEnumerable<string> results =
from dt in dts
let x = DateTime.TryParseExact(dt, formatStrings, enUS, DateTimeStyles.None, out DateTime dateValue) ? (DateTime?)dateValue : null
where x != null
select x.Value.ToString("dd/MM/yyy");
It produces:
30/07/2022
30/07/2022
07/11/2022