[英]Check if a string is a valid date using DateTime.TryParse
I am using DateTime.TryParse()
function to check if a particular string is a valid datetime not depending on any cultures.我正在使用
DateTime.TryParse()
函数来检查特定字符串是否是不依赖于任何文化的有效日期时间。
To my surprise , the function returns true
for even strings like "1-1", "1/1" .etc.令我惊讶的是,该函数对于“1-1”、“1/1”等偶数字符串返回
true
。
How can I solve this problem?我怎么解决这个问题?
Update:更新:
Does it mean, if I want to check if a particular string is valid datetime, I need a huge array of formats??这是否意味着,如果我想检查特定字符串是否为有效日期时间,我需要大量格式? There will be different combinations , I believe.
我相信会有不同的组合。
Even there are lots of date separator ( '.' , '/' , '-', etc..) depending on the culture, it will be difficult for me to define an array of format to check against .即使有很多日期分隔符( '.' 、 '/' 、 '-' 等)取决于文化,我也很难定义一组格式来检查 .
Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution?基本上,我想检查一个特定的字符串是否以任何顺序包含至少一天(1 到 31 或 01 到 31)、月(1 到 12 或 01 到 12)和年(yyyy 或 yy),带有任何日期分隔符,解决办法是什么?
So, if the value includes any parts of time, it should return true too.因此,如果该值包含时间的任何部分,它也应该返回 true。 I could NOT be able to define a array of format.
我无法定义格式数组。
If you want your dates to conform a particular format or formats then use DateTime.TryParseExact
otherwise that is the default behaviour of DateTime.TryParse
如果你希望你的日期,以符合特定的格式或格式,然后使用
DateTime.TryParseExact
否则就是默认行为DateTime.TryParse
DateTime.TryParse日期时间.TryParse
This method tries to ignore unrecognized data , if possible, and fills in missing month, day, and year information with the current date.
如果可能,此方法会尝试忽略无法识别的数据,并使用当前日期填充缺失的月、日和年信息。 If s contains only a date and no time, this method assumes the time is 12:00 midnight.
如果 s 仅包含日期而没有时间,则此方法假定时间为午夜 12:00。 If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property.
如果 s 包含具有两位数年份的日期组件,则它会根据 Calendar.TwoDigitYearMax 属性的值转换为当前区域性的当前日历中的年份。 Any leading, inner, or trailing white space character in s is ignored.
s 中的任何前导、内部或尾随空白字符都将被忽略。
If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload.如果您想针对多种格式进行确认,请查看DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime)重载。 Example from the same link:
来自同一链接的示例:
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);
}
// The example displays the following output:
// Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
// Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
Use DateTime.TryParseExact()
if you want to match against a specific date format如果要匹配特定日期格式,请使用
DateTime.TryParseExact()
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
{
Console.WriteLine(dateTime);
}
else
{
Console.WriteLine("Not a date");
}
[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
string[] formats = { "MM/dd/yyyy" };
DateTime parsedDateTime;
return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
DateTimeStyles.None, out parsedDateTime);
}
Simply specify the date time formats that you wish to accept in the array named formats .只需在名为format的数组中指定您希望接受的日期时间格式。
I solved the problem with the following code: 我用以下代码解决了这个问题:
protected bool CheckDate(String date)
{
try
{
DateTime dt = DateTime.Parse(date);
return true;
}
catch
{
return false;
}
}
So this question has been answered but to me the code used is not simple enough or complete.所以这个问题已经得到回答,但对我来说使用的代码不够简单或完整。 To me this bit here is what I was looking for and possibly some other people will like this as well.
对我来说,这就是我一直在寻找的东西,可能其他一些人也会喜欢这个。
string dateString = "198101";
if (DateTime.TryParse(dateString, out DateTime Temp) == true)
{
//do stuff
}
The output is stored in Temp
and not needed afterwards, datestring
is the input string to be tested.输出存储在
Temp
,之后不需要, datestring
是要测试的输入字符串。
Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution?
基本上,我想检查一个特定的字符串是否以任何顺序包含至少一天(1 到 31 或 01 到 31)、月(1 到 12 或 01 到 12)和年(yyyy 或 yy),带有任何日期分隔符,解决办法是什么? So, if the value includes any parts of time, it should return true too.
因此,如果该值包含时间的任何部分,它也应该返回 true。 I could NOT be able to define a array of format.
我无法定义格式数组。
When I was in a similar situation, here is what I did:当我处于类似情况时,我是这样做的:
This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple was really helpful both for understanding as well as validation the syntax for each format.这个http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple对于理解和验证每种格式的语法非常有帮助。
My 2 cents if it helps....如果有帮助,我的 2 美分...
Try using尝试使用
DateTime.ParseExact(
txtPaymentSummaryBeginDate.Text.Trim(),
"MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture
);
It throws an exception if the input string is not in proper format, so in the catch
section you can return false;
如果输入字符串的格式不正确,它会抛出异常,因此在
catch
部分您可以return false;
An alternative is to create a method to validate that the text is of Date type.另一种方法是创建一种方法来验证文本是否为日期类型。
public bool IsDateTime(string date)
{
if (string.IsNullOrEmpty(date)) return false;
return DateTime.TryParse(date, out DateTime dateTime);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.