且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串转换为有效日期时间

更新时间:2023-02-03 15:35:55

嗯,presumably你的线程的当前区域性预计MM / DD / YYYY。如果你想使用DD / MM / YYYY那么你应该明确指定。我个人preFER ParseExact 而不是解析,因为这提供了更多的控制权。我会用这样的:

Well, presumably your thread's current culture expects MM/dd/yyyy. If you want to use dd/MM/yyyy then you should specify that explicitly. Personally I prefer ParseExact instead of Parse, as that gives more control. I would use something like:

DateTime dt = DateTime.ParseExact(strdate, "dd/MM/yyyy",
    CultureInfo.InvariantCulture);

请注意,如果这是用户的输入,您可能需要使用 TryParseExact 代替。

Note that if this is user input, you may want to use TryParseExact instead.