简体   繁体   English

DateTime.TryParse 将十进制转换为日期时间

[英]DateTime.TryParse converts decimal to datetime

The following line of code return true (which it should not)....and convert 1.0228 into datetime...以下代码行返回 true(它不应该)......并将 1.0228 转换为日期时间......

DateTime.TryParse(1.0228,out temporaryDateTimeValue)

Somebody please help me.有人请帮助我。

The following line of code return true (which it should not)....and convert 1.0228 into datetime...以下代码行返回 true(它不应该)......并将 1.0228 转换为日期时间......

DateTime.TryParse(1.0228,out temporaryDateTimeValue)

This will not compile.这不会编译。

However, if you wrap it in quotes (and clean it up a little bit),但是,如果你用引号括起来(并稍微清理一下),

bool success = DateTime.TryParse("1.0228", out temporaryDateTimeValue);

then, yes, you will get true back.那么,是的,你会得到true回报。 You need to read the documentation to understand why, but basically, there are many different ways to format dates and you stumbled on one (maybe M.yyyy ?).您需要阅读文档以了解原因,但基本上,有许多不同的格式化日期的方法,您偶然发现了一种(可能M.yyyy ?)。

If you don't want it to parse, may I suggest如果您不希望它解析,我可以建议

bool success = DateTime.TryParseExact(
                   "1.0228",
                   "yyyyMMdd", 
                   CultureInfo.InvariantCulture,
                   DateTimeStyles.None,
                   out temporaryDateTimeValue
               );

Then success is false .那么successfalse的。

I note from the remarks in the documentation :我从文档中的注释中注意到:

The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture.字符串s使用当前DateTimeFormatInfo object 中的格式信息进行解析,该信息由当前线程区域性隐式提供。

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。 Any leading, inner, or trailing white space character in s is ignored. s 中的任何前导、内部或尾随空白字符都将被忽略。 The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000).日期和时间可以用一对前导和尾随数字符号字符('#',U+0023)括起来,并且可以用一个或多个 NULL 字符(U+0000)结尾。

Because the DateTime.TryParse(String, DateTime) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results.由于DateTime.TryParse(String, DateTime)方法尝试使用当前区域性的格式规则解析日期和时间的string表示,因此尝试跨不同区域性解析特定string可能会失败或返回不同的结果。 If a specific date and time format will be parsed across different locales, use the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method or one of the overloads of the TryParseExact method and provide a format specifier.如果将跨不同的语言环境解析特定的日期和时间格式,请使用DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime)方法或TryParseExact方法的重载之一并提供格式说明符。

Basically, TryParse "tries" very hard to parse the string you give it (although the " Try " really refers to the fact that the method returns a bool for success/failure indication).基本上, TryParse “尝试”解析你给它的字符串(尽管“ Try ”实际上是指该方法返回一个布尔值以指示成功/失败指示的事实)。

No, that code doesn't return true - it doesn't even compile:不,该代码不会返回 true - 它甚至不会编译:

using System;

class Program
{

    static void Main(string[] args)
    {
        DateTime dt;
        Console.WriteLine(DateTime.TryParse(1.0228, out dt));
    }
}

Error:错误:

Test.cs(9,27): error CS1502: The best overloaded method match for
        'System.DateTime.TryParse(string, out System.DateTime)' has some invalid
        arguments
Test.cs(9,45): error CS1503: Argument 1: cannot convert from 'double' to
        'string'

If you change it to "1.0228" it does return true, yes.如果将其更改为“1.0228”,它返回 true,是的。 It looks like it's using a format of "M.yyyy", which is no doubt valid for some cultures... and highlights why it's a bad idea to use DateTime.TryParse in my view.看起来它使用的是“M.yyyy”格式,这无疑对某些文化有效......并强调了为什么在我看来使用DateTime.TryParse是个坏主意。 If you've got a specific format (or set of formats) in mind, you should useDateTime.TryParseExact instead so you can specify the format.如果您有特定的格式(或格式集),您应该使用DateTime.TryParseExact代替,以便您可以指定格式。

I usually find it's a good idea to specify the exact format, and I usually also specify CultureInfo.InvariantCulture unless the date is coming directly from the user (which is rare, in my experience).我通常发现指定确切的格式是个好主意,而且我通常还会指定CultureInfo.InvariantCulture ,除非日期直接来自用户(根据我的经验,这种情况很少见)。

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

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