Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

datetime - Find out the Date time format of string date in c#

I am making an application. The application uses date format such as "2012-11-21 15:22:35".
I already know that the format is "yyyy-MM-dd HH:mm:ss". But how can I find programmatically the date & time format of an arbitrary input string? Is there any way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This might help you.. (in the array, add more formats to check)

string[] formats = {"M/d/yyyy", "MM/dd/yyyy",                                    
                            "d/M/yyyy", "dd/MM/yyyy", 
                            "yyyy/M/d", "yyyy/MM/dd",
                            "M-d-yyyy", "MM-dd-yyyy",                                    
                            "d-M-yyyy", "dd-MM-yyyy", 
                            "yyyy-M-d", "yyyy-MM-dd",
                            "M.d.yyyy", "MM.dd.yyyy",                                    
                            "d.M.yyyy", "dd.MM.yyyy", 
                            "yyyy.M.d", "yyyy.MM.dd",
                            "M,d,yyyy", "MM,dd,yyyy",                                    
                            "d,M,yyyy", "dd,MM,yyyy", 
                            "yyyy,M,d", "yyyy,MM,dd",
                            "M d yyyy", "MM dd yyyy",                                    
                            "d M yyyy", "dd MM yyyy", 
                            "yyyy M d", "yyyy MM dd"
                           };

        DateTime dateValue;

        foreach (string dateStringFormat in formats)
        {
            if (DateTime.TryParseExact(strDateTime, dateStringFormat,
                                       CultureInfo.InvariantCulture,
                                       DateTimeStyles.None,
                                       out dateValue))
                //Console.WriteLine("Converted '{0}' to {1}.", dateStringFormat, dateValue.ToString("yyyy-MM-dd"));                
                Console.WriteLine( dateStringFormat);
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...