简体   繁体   English

测试将字符串转换为日期时间,而不是DateTime.TryParseExact

[英]Test convert string to date time other than DateTime.TryParseExact

Good day, 美好的一天,

Normally, If I want to test whether a string is a valid date time format, I will use : 通常,如果我要测试字符串是否为有效的日期时间格式,我将使用:

if (DateTime.TryParseExact()){
//do something
}

I would like to ask, is there any code can direct test Convert.ToDateTime() is successful or not? 我想问一下,是否有任何代码可以直接测试Convert.ToDateTime()是否成功? For example like : 例如:

if (Convert.ToDateTime(date1)){
//do something
}

or 要么

if(Convert.ToDateTime(date1) == true){
//do soemthing
}

My idea is make it become bool to test it successful convert to date time or not. 我的想法是使它成为布尔型,以测试是否成功将其转换为日期时间。 Just trying to find out the code instead of using DateTime.TryParseExact() 只是试图找出代码,而不是使用DateTime.TryParseExact()

Your first code 您的第一个代码

if (DateTime.TryParseExact()) {
    //do something
}

does exactly what you want. 正是您想要的。

Use it like this: 像这样使用它:

if (DateTime.TryParseExact(str, ...)) {    // OR use DateTime.TryParse()
    // str is a valid DateTime
}
else {
    // str is not valid
}

You may use DateTime.TryParse() if you don't want to provide a format. 如果不想提供格式,则可以使用DateTime.TryParse()
Both methods returns a bool ean value. 两种方法均返回bool值。

If you really want to you can use convert to. 如果您确实想要,可以使用convert to。 However using this means you do not get the features that tryparse can give you. 但是,使用此方法意味着您无法获得tryparse可以提供的功能。

TryParse: 的TryParse:

-Simple if/else validation -简单的if / else验证

-Wont crash and burn your app if bad data is put into it -如果将不良数据放入应用程序中,它不会崩溃并刻录您的应用程序

public static bool
{ 
    TryParse(string s, out DateTime result)
}

Then if else validation 然后如果其他验证

ConvertTo: 转换成:

-If bad data is put in, your app will crash -如果输入错误数据,您的应用将崩溃

-Better to include a try catch into this -最好在其中加入尝试

-See the msdn article on ConvertTo -请参阅有关ConvertTomsdn文章

 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);
  }
}

In my eyes you should always preference to Tryparse. 在我眼中,您应该始终偏爱Tryparse。

As per your comments: 根据您的评论:

I need to declare a format to check, sometimes the date time format maybe different, thats why I am thinking is there any code like what I think. 我需要声明一种格式进行检查,有时日期时间格式可能会有所不同,这就是为什么我在考虑是否有任何类似我所认为的代码。

TryParseExact already takes a format. TryParseExact已采用一种格式。

This short example does what you want using TryParseExact . 这个简短的示例使用TryParseExact实现了您想要的功能。 TryParseExact won't throw an exception if the format or date is wrong so you don't have to worry about expensive Try/Catch blocks. 如果格式或日期错误, TryParseExact不会引发异常,因此您不必担心昂贵的Try/Catch块。 Instead it will return false . 相反,它将返回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;
   }
}

Or shortened: 或缩短:

public static bool ValidateDate(string date, string format)
{
    DateTime dateTime;
    return DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
}

Then use something like this. 然后使用这样的东西。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM