它工作得很好多年,直到有人試圖提交 三部分版本號。突然1.3.1變成了2001-03-01和 比較停止工作。
這將是你應該使用的DateTime ParseExact(字符串s,字符串格式,的IFormatProvider povider)
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
// Parse date-only value without leading zero in month using "d" format.// Should throw a FormatException because standard short date pattern of // invariant culture requires two-digit month.
dateString = "6/15/2008";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
// Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
// Parse date and time with offset but without offset's minutes. // Should throw a FormatException because "zzz" specifier requires leading // zero in hours.
dateString = "Sun 15 Jun 2008 8:30 AM -06";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
dateString = "15/06/2008 08:30";
format = "g";
provider = new CultureInfo("fr-FR");
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
}
}
Source
我認爲沒有通用的方法來做到這一點。想象一下有效的日期,也可以是有效的版本:1.12.2012或者......可以是日期,也可以是s.b.的版本。每增加一個版本都會增加版本號。 – dognose
您希望支持哪些輸入日期格式(視爲有效輸入)? dd/MM/yyyy,MM/dd/yyyy等? – giacomelli
您爲什麼擔心時間和日期格式不適用於您的客戶?如果你使用'DateTime.ParseExact',你可以忽略任何不適用於你的客戶端的格式。 –