There is a SQL Server 2008 database for which I have to create a management software. The database contains a column named DateOfCreation. The table designer made this column as string and gave freedom to users to add date in any format they want and this was really a silly mistake by him. Now some users added as "24 Jan" or "Jan 24" or "1991 1 12" and many unknown formats. What I want is that when I fetch this string date, a function should be called that will check the format and return -1 if date is not in correct format else return the converted date in DD/MM/YYYY. So how can I check the format of the date that string date variable is containing?
質問する
1842 次
3 に答える
5
use DateTime.TryParseExact
with your date format, it will return false in case if the date format is different or invalid.
For multiple formats you can specify multiple formats in a string array and then use that in DateTime.TryParseExact
something like:
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
could help to some extent. However, you would be dependent on your user using an appropriate date/time format.
于 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)
}
may work. I can't guarantee it though.
于 2013-01-27T16:52:34.727 に答える