简体   繁体   English

转换前检查字符串是否为日期时间的最佳做法?

[英]Best practice in checking if a string is a datetime before converting?

What's the best way to do it? 最好的方法是什么?

This is how I'll usually do it: 这就是我通常会这样做的方式:

DateTime newDate;

try
{
    newDate = DateTime.Parse(Textbox.Text);
}
catch
{
    //isn't a datetime
    return;
}

//do stuff with the date

But something tells me that that is a bit wrong. 但有些事情告诉我,这有点不对劲。 Any ideas? 有任何想法吗?

Use the DateTime.TryParse method instead of using your own try/catch blocks. 使用DateTime.TryParse方法而不是使用自己的try / catch块。

string text = "10/16/2009";
DateTime result;

if (DateTime.TryParse(text, out result))
{
    // success, result holds converted value
}
else
{
    // failed
}

The best pattern to use for datetime parsing would be this 用于日期时间解析的最佳模式是这样的

string DateFormat = "dd/MM/yyyy"; //Or any other format
DateTime dateTime;
bool success = DateTime.TryParseExact(value, DateFormat, 
       CultureInfo.InvariantCulture, 
           DateTimeStyles.None, 
                out dateTime);

Never use DateTime.Parse and even DateTime.TryParse 永远不要使用DateTime.Parse甚至DateTime.TryParse

If you know what the format of the datetime will be, you can also use DateTime..::.TryParseExact Method 如果你知道datetime的格式是什么,你也可以使用DateTime .. ::。TryParseExact方法

The DateTime.TryParse can cause problems when it is used with dates such as 01/03/2009 DateTime.TryParse与日期(例如01/03/2009)一起使用时可能会导致问题

Is it 01 Mar or 03 Jan? 是3月1日或1月3日?

I would rather recomend that you use something other than a textbox, like a date picker, or validate the textbox so that you have something like dd MMM yyyy. 我宁愿建议您使用文本框之外的其他内容,例如日期选择器,或者验证文本框,以便您拥有像MM MMYyyy这样的东西。 very seldomly would you go wrong with that. 你很少会出错。

Little addition to previous answers: 以前的答案很少:

DateTime: 约会时间:

public static DateTime Parse(string s)
{
    return DateTimeParse.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None);
}

public static bool TryParse(string s, out DateTime result)
{
    return DateTimeParse.TryParse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result);
}

DateTimeParse: DateTimeParse:

internal static DateTime Parse(string s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
{
    DateTimeResult result = new DateTimeResult();
    result.Init();
    if (!TryParse(s, dtfi, styles, ref result))
    {
        throw GetDateTimeParseException(ref result);
    }
    return result.parsedDate;
}

TryParse is better TryParse更好

References: 参考文献:

Reflector 反光

Try the following: 请尝试以下方法:

DateTime todate;
if(!DateTime.TryParse("2009/31/01", todate))
{
//------------conversion failed-------------//
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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