Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Date multiple format conversion in .net framework

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EXPECTED OUTPUT:  30/07/2022  for i & ii
                  07/11/2022  for iii

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading