Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
class Program
    {

        static void Main(string[] args)
        {
            string date = "19890428";
            DateTime dateTime;
            string[] format = { "MMddyyyy", "ddMMyyyy", "yyyyMMdd", "yyyyddMM" };
            if (DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture,
                   DateTimeStyles.None, out dateTime))
            {
                Console.WriteLine( "yes" );
            }

            Console.ReadLine();

        }
    }


I get output "yes" -- by looking at the format i can know that it is yyyyMMdd so it is passed in if condition.

Is there a way to know at runtime that which format is passed.
We are consuming a webservice and the format that we are getting are not sure.It always comes as string. I don't want to do if else to check which format got passed and convert accordingly as below.  

var x = DateTime.ParseExact(cd13, "yyyyddMM", CultureInfo.InvariantCulture);

Kindly suggest.
Posted
Updated 22-Sep-15 0:24am
v4

1 solution

The "multiple format" version of DateTime.TryParseExact does not give you any information on which format was matched - it just returns true if any one was matched, and false if none of them were.

If you need to know which format it was, your only method is to call it repeatedly with each format in turn until you either get a match, or run out of format strings.

But...that's dangerous - you should be using the Culture that the user is entering in (or better prompt him for the day, month, and year separately). With your code, "05122012" will always be recognised as the 12th of May, even if the user intended the 5th of December.
 
Share this answer
 
Comments
anurag19289 22-Sep-15 7:20am    
yaa that seems correct, we cant get which format is matched.

And also the UI is not handled from our end :) we are contacting the owner of the service to send only singly format, so that there will be no confusion at our end.
OriginalGriff 22-Sep-15 7:33am    
See if you can get them to send it as a UTC DateTime value instead of a string (and UTC if they can only provide a string) - that way it eliminates any potential confusion from local time zones as well.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900