![](/img/trans.png)
[英]Use DateTime.TryParseExact to format date string and ignore time
[英]Test convert string to date time other than DateTime.TryParseExact
美好的一天,
通常,如果我要测试字符串是否为有效的日期时间格式,我将使用:
if (DateTime.TryParseExact()){
//do something
}
我想问一下,是否有任何代码可以直接测试Convert.ToDateTime()是否成功? 例如:
if (Convert.ToDateTime(date1)){
//do something
}
要么
if(Convert.ToDateTime(date1) == true){
//do soemthing
}
我的想法是使它成为布尔型,以测试是否成功将其转换为日期时间。 只是试图找出代码,而不是使用DateTime.TryParseExact()
您的第一个代码
if (DateTime.TryParseExact()) {
//do something
}
正是您想要的。
像这样使用它:
if (DateTime.TryParseExact(str, ...)) { // OR use DateTime.TryParse()
// str is a valid DateTime
}
else {
// str is not valid
}
如果不想提供格式,则可以使用DateTime.TryParse()
。
两种方法均返回bool
值。
如果您确实想要,可以使用convert to。 但是,使用此方法意味着您无法获得tryparse可以提供的功能。
的TryParse:
-简单的if / else验证
-如果将不良数据放入应用程序中,它不会崩溃并刻录您的应用程序
public static bool
{
TryParse(string s, out DateTime result)
}
然后如果其他验证
转换成:
-如果输入错误数据,您的应用将崩溃
-最好在其中加入尝试
-请参阅有关ConvertTo的msdn文章
private static void ConvertToDateTime(string value)
{
DateTime convertedDate;
try {
convertedDate = Convert.ToDateTime(value);
Console.WriteLine("'{0}' converts to {1} {2} time.",
value, convertedDate,
convertedDate.Kind.ToString());
}
catch (FormatException) {
Console.WriteLine("'{0}' is not in the proper format.", value);
}
}
在我眼中,您应该始终偏爱Tryparse。
根据您的评论:
我需要声明一种格式进行检查,有时日期时间格式可能会有所不同,这就是为什么我在考虑是否有任何类似我所认为的代码。
TryParseExact
已采用一种格式。
这个简短的示例使用TryParseExact实现了您想要的功能。 如果格式或日期错误, TryParseExact
不会引发异常,因此您不必担心昂贵的Try/Catch
块。 相反,它将返回false
。
static void Main()
{
Console.Write(ValidateDate("ddd dd MMM h:mm tt yyyy", "Wed 10 Jul 9:30 AM 2013"));
Console.Read();
}
public static bool ValidateDate(string date, string format)
{
DateTime dateTime;
if (DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
Console.WriteLine(dateTime);
return true;
}
else
{
Console.WriteLine("Invalid date or format");
return false;
}
}
或缩短:
public static bool ValidateDate(string date, string format)
{
DateTime dateTime;
return DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
}
然后使用这样的东西。
bool isDateTimeValid(string date, string format)
{
try
{
DateTime outDate = DateTime.ParseExact(date, format, Thread.CurrentThread.CurrentUICulture);
return true;
}
catch(Exception exc)
{
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.