如何检查字符串日期是否可以转换为日期时间

本文关键字:日期 是否 转换 时间 字符串 何检查 检查 | 更新日期: 2023-09-27 17:56:08

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

如何检查字符串日期是否可以转换为日期时间

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

对于多种格式,

您可以在字符串数组中指定多种格式,然后在DateTime.TryParseExact中使用它,如下所示:

From MSDN - DateTime.TryParseExact Method (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);
}

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

public Tuple<bool, DateTime> GetDateTime(string x)
{
DateTime DT = null;
return Tuple.Create((DateTime.TryParse(x, out DT)), DT)
}

可能有效。不过我不能保证。