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

发布于 2024-11-17 17:11:28 字数 145 浏览 2 评论 0原文

下面的代码行返回 true (它不应该)...并将 1.0228 转换为日期时间...

DateTime.TryParse(1.0228,out temporaryDateTimeValue)

请有人帮助我。

The following line of code return true (which it should not)....and convert 1.0228 into datetime...

DateTime.TryParse(1.0228,out temporaryDateTimeValue)

Somebody please help me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

辞旧 2024-11-24 17:11:28

以下代码行返回 true(不应该)...并将 1.0228 转换为日期时间...

DateTime.TryParse(1.0228,out temporaryDateTimeValue)

这将无法编译。

但是,如果您将其用引号引起来(并稍微清理一下),

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

那么,是的,您将得到 true 。您需要阅读文档才能理解原因,但基本上,有许多不同的方法来格式化日期,您偶然发现了一种(也许M.yyyy?)。

如果您不希望它解析,我可以建议

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

那么successfalse

我从文档中的评论中注意到:

使用当前 DateTimeFormatInfo 对象中的格式信息来解析字符串 s,该对象由当前线程区域性隐式提供。

如果可能,此方法会尝试忽略无法识别的数据,并使用当前日期填充缺失的月、日和年信息。如果 s 仅包含日期而不包含时间,则此方法假定时间为午夜 12:00。 s 中的任何前导、内部或尾随空白字符都将被忽略。日期和时间可以用一对前导和尾随数字符号字符(“#”、U+0023)括起来,并且可以用一个或多个 NULL 字符(U+0000)结尾。

因为 DateTime.TryParse(String, DateTime) 方法尝试使用当前区域性的格式规则来解析日期和时间的 string 表示形式,尝试跨不同文化解析特定的字符串可能会失败或返回不同的结果。如果要跨不同区域设置解析特定的日期和时间格式,请使用 DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) 方法或 TryParseExact 方法并提供格式说明符。

基本上,TryParse 非常努力地“尝试”解析您给它的字符串(尽管“Try”实际上指的是该方法返回一个布尔值来表示成功/失败指示)。

The following line of code return true (which it should not)....and convert 1.0228 into datetime...

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. 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?).

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.

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.

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. Any leading, inner, or trailing white space character in s is ignored. 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).

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. 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.

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).

若水微香 2024-11-24 17:11:28

不,该代码不会返回 true - 它甚至无法编译:

using System;

class Program
{

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

错误:

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'

如果将其更改为“1.0228”,它确实会返回 true,是的。看起来它使用的是“M.yyyy”格式,这无疑对某些文化有效......并强调了为什么在我看来使用 DateTime.TryParse 是一个坏主意。如果您考虑了特定格式(或一组格式),则应使用 DateTime.TryParseExact 代替,以便您可以指定格式。

我通常发现指定确切的格式是一个好主意,并且我通常还会指定 CultureInfo.InvariantCulture 除非日期直接来自用户(这种情况很少见,在我的经验)。

No, that code doesn't return true - it doesn't even compile:

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. 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. If you've got a specific format (or set of formats) in mind, you should use DateTime.TryParseExact instead so you can specify the format.

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文