Shi*_*eek 0 c# sql-server asp.net datetime sql-server-2008
有一个SQL Server 2008数据库,我必须为其创建一个管理软件.该数据库包含名为DateOfCreation的列.表设计者将此列作为字符串,并允许用户以他们想要的任何格式添加日期,这实际上是他的一个愚蠢的错误.现在一些用户添加了"1月24日"或"1月24日"或"1991 1 12"以及许多未知格式.我想要的是,当我获取此字符串日期时,应该调用一个函数来检查格式,如果日期格式不正确则返回-1,否则返回DD/MM/YYYY中的转换日期.那么我该如何检查字符串日期变量包含的日期格式呢?
使用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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1462 次 |
| 最近记录: |