0

有一个 SQL Server 2008 数据库,我必须为其创建一个管理软件。该数据库包含一个名为 DateOfCreation 的列。表格设计者将此列设为字符串,并允许用户以他们想要的任何格式添加日期,这确实是他的一个愚蠢的错误。现在一些用户添加了“24 Jan”或“Jan 24”或“1991 1 12”等许多未知格式。我想要的是,当我获取这个字符串日期时,应该调用一个函数来检查格式,如果日期格式不正确则返回 -1,否则返回 DD/MM/YYYY 中的转换日期。那么如何检查字符串日期变量包含的日期格式呢?

4

3 回答 3

5

与您的日期格式一起使用DateTime.TryParseExact,如果日期格式不同或无效,它将返回 false。

对于多种格式,您可以在字符串数组中指定多种格式,然后在以下内容中使用它DateTime.TryParseExact

来自 MSDN - DateTime.TryParseExact 方法(String、String[]、IFormatProvider、DateTimeStyles、DateTime%)

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);
}
于 2013-01-27T16:44:14.857 回答
3

DateTime.TryParse可以在一定程度上有所帮助。但是,您将依赖于您的用户使用适当的日期/时间格式。

于 2013-01-27T16:44:36.160 回答
1
public Tuple<bool, DateTime> GetDateTime(string x)
{
DateTime DT = null;
return Tuple.Create((DateTime.TryParse(x, out DT)), DT)
}

可能工作。不过我不能保证。

于 2013-01-27T16:52:34.727 回答