Checking Date format from a string in C#

2019-02-16 08:30发布

I want to check whether a string contains dates such as 1/01/2000 and 10/01/2000 in dd/MM/yyyy format.

So far I have tried this.

DateTime dDate = DateTime.Parse(inputString);
string.Format("{0:d/MM/yyyy}", dDate); 

But how can I check if that format is correct to throw an exception?

8条回答
一夜七次
2楼-- · 2019-02-16 09:12

Use an array of valid dates format, check docs:

string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);

if(isValidFormat)
{
    string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
    // maybe throw an Exception
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-16 09:17

I think one of the solutions is to use DateTime.ParseExact or DateTime.TryParseExact

DateTime.ParseExact(dateString, format, provider);

source: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

查看更多
淡お忘
4楼-- · 2019-02-16 09:17

you could always try:

Regex r = new Regex(@"\d{2}/\d{2}/\d{4}");

r.isMatch(inputString);

this will check that the string is in the format "02/02/2002" you may need a bit more if you want to ensure that it is a valid date like dd/mm/yyyy

查看更多
时光不老,我们不散
5楼-- · 2019-02-16 09:19

https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                     "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                     "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                     "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                     "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
  string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                          "5/1/2009 6:32:00", "05/01/2009 06:32", 
                          "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
  DateTime dateValue;

  foreach (string dateString in dateStrings)
  {
     if (DateTime.TryParseExact(dateString, formats, 
                                new CultureInfo("en-US"), 
                                DateTimeStyles.None, 
                                out dateValue))
        Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
     else
        Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
  }
查看更多
放荡不羁爱自由
6楼-- · 2019-02-16 09:19

Datetime dt=datetime.parse(string); string out=dt.tostring("dd/MM/yyyy");

查看更多
戒情不戒烟
7楼-- · 2019-02-16 09:22
string inputString = "2000-02-02";
DateTime dDate;

if (DateTime.TryParse(inputString, out dDate))
{
    String.Format("{0:d/MM/yyyy}", dDate); 
}
else
{
    Console.WriteLine("Invalid"); // <-- Control flow goes here
}
查看更多
登录 后发表回答