日期时间格式异常错误

发布于 2024-12-04 01:55:37 字数 175 浏览 1 评论 0原文

DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);

txtDatumDokum.Text 就像“09.09.2011”。

但我收到 FormatException 错误。我必须解析日期吗?

DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);

txtDatumDokum.Text is like "09.09.2011".

but i get FormatException error. Must i parse date?

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

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

发布评论

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

评论(9

望笑 2024-12-11 01:55:37

尝试使用 dd.MM.yyyy 格式字符串的 DateTime.ParseExact

 DateTime.ParseExact(txtDatumDokum.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);

Try DateTime.ParseExact with the dd.MM.yyyy format string

 DateTime.ParseExact(txtDatumDokum.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
柠檬 2024-12-11 01:55:37

看起来不太好,无论如何尝试一下:

string s = "09.09.2011";
DateTime dt = Convert.ToDateTime(
    s.Replace(".",
    new System.Globalization.DateTimeFormatInfo().DateSeparator));

It's not good to see, anyway try this:

string s = "09.09.2011";
DateTime dt = Convert.ToDateTime(
    s.Replace(".",
    new System.Globalization.DateTimeFormatInfo().DateSeparator));
烟燃烟灭 2024-12-11 01:55:37

您需要告诉我们为什么文本输入使用这种格式。如果是因为用户以这种方式输入,那么您需要确保格式与 Thread.CurrentCulture.DateTimeFormat.ShortDatePattern。改变文化(通过设置
Thread.CurrentCulture) 到适当的值将解决您的问题。

如果您应该解析输入,无论它是什么格式,那么您将需要首先进行一些手动处理(也许使用 string.Replace 从输入中删除空格和其他分隔符)并且然后尝试使用 DateTime.ParseExact 和已知的格式字符串。

但这完全取决于为什么输入具有该格式,以及为什么应用程序的当前区域性与它不匹配。

You need to tell us why the text input is using this format. If it is because the user enters it this way, then you need to make sure that the format matches that given by Thread.CurrentCulture.DateTimeFormat.ShortDatePattern. Changing the culture (by setting
Thread.CurrentCulture) to an appropriate value will then solve your problem.

If you are supposed to parse the input no matter what format it is in, then you will need to do some manual processing first (perhaps remove spaces and other delimiter characters from the input with string.Replace) and then try to parse the date using DateTime.ParseExact and a known format string.

But it all depends on why the input has that format, and why your application's current culture does not match it.

木格 2024-12-11 01:55:37

您可以尝试这个,TryParse 避免解析异常。然后您只需要检查结果以确保它已解析。

DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, out datuMDokumenta);

您必须确定这是否是适合您的应用程序的良好解决方案。

看这个例子:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

根据您提供的日期判断,您需要包含一种文化,de-DE 接受 01.01.11 类型的日期,但我不确定您实际想要使用哪一个,您需要来决定......代码将如下所示:

using System.Globalization;

DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, CultureInfo.CreateSpecificCulture("de-DE"), DateTimeStyles.None, out datuMDokumenta);

可以在此处找到文化列表,选择适合您的文化:
http://msdn.microsoft .com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx

这里的优点是这段代码工作量更大,但很难破解。假设您在 TextBox 上使用自由文本条目,您不希望引发异常。

You could try this, TryParse avoids parsing exceptions.. Then you just need check result to be sure that it parsed.

DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, out datuMDokumenta);

You will have to determine if this is a good solution for your application.

See this example:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

Judging by the date you gave you need to include a culture, de-DE accepts 01.01.11 type of dates but I'm not sure which one you actually want to use, you'll need to decide that.. the Code would look like this:

using System.Globalization;

DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, CultureInfo.CreateSpecificCulture("de-DE"), DateTimeStyles.None, out datuMDokumenta);

A list of cultures can be found here, select the appropriate one for you:
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx

The plus here is that this code is a bit more work but it is very difficult to break. Assuming you are using a free text entry on a TextBox you don't want to be throwing exceptions.

生生漫 2024-12-11 01:55:37

是的,您必须解析当前文化中的输入日期。

string[] format = new string[] { "dd.MM.yyyy" };
string value = "09.09.2011";
DateTime datetime;

if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out datetime))
      //Valid
else
     //Invalid

Yes you have to parse input date in current culture.

string[] format = new string[] { "dd.MM.yyyy" };
string value = "09.09.2011";
DateTime datetime;

if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out datetime))
      //Valid
else
     //Invalid
甜味拾荒者 2024-12-11 01:55:37

DateTime dt = Convert.ToDateTime(txtDatumDokum.Text)

是的...没有问题

DateTime dt = Convert.ToDateTime(txtDatumDokum.Text)

It is right...there is no isssue

农村范ル 2024-12-11 01:55:37

在紧凑框架 3.5 下的反序列化调用期间,我之前遇到过一些意外行为。

我已从使用 OpenNETCF 序列化类转换为使用框架 XML 序列化类。这样做时,默认时间格式以及属性/公共成员的顺序都已更改。长话短说,我公开了一个文本属性,它将我的日期时间转换回我的 VB6 应用程序期望的格式。

            Dim dumbDate As New Date
            Dim formats() As String = {"yyyy-MM-ddTHH:mm:ss.fffzzz", _
                                       "yyyy-MM-dd HH:mm:ss:fffffffzzz"}

            _datetimeTaken = dumbDate.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)

            ' There is something wrong with compact framework during the Serialization calls. 
            ' calling the shared method Date.Parse or Date.ParseExact does not produce the same
            ' result as calling a share method on an instance of Date. WTF?!?!?!
            ' The below will cause a "Format" exception.
            '_datetimeTaken = Date.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)

Date.blah 不起作用。 dumbDate.blah 有效。奇怪的。

During a Deserialization call under compact framework 3.5 i've had some unexpected behaviour before.

I've converted from using the OpenNETCF serialization classes to the framework XML serialization class. In doing so, the default time format has changed and the order of property/public members. So long story short, i've exposed a text property which converts my date-times back to the format my VB6 application is expecting.

            Dim dumbDate As New Date
            Dim formats() As String = {"yyyy-MM-ddTHH:mm:ss.fffzzz", _
                                       "yyyy-MM-dd HH:mm:ss:fffffffzzz"}

            _datetimeTaken = dumbDate.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)

            ' There is something wrong with compact framework during the Serialization calls. 
            ' calling the shared method Date.Parse or Date.ParseExact does not produce the same
            ' result as calling a share method on an instance of Date. WTF?!?!?!
            ' The below will cause a "Format" exception.
            '_datetimeTaken = Date.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)

Date.blah doesn't work. dumbDate.blah works. strange.

烟织青萝梦 2024-12-11 01:55:37
    public static void Main(string[] args)
    {
        var dt = new DateTime(2018, 04, 1);
        Console.WriteLine(dt);
       
        string month = dt.ToString("MMMM");
        Console.WriteLine(month);               //April

        month = dt.ToString("MMM");
        Console.WriteLine(month);              //Apr

        month = dt.ToString("MM");
        Console.WriteLine(month);             //04

        Console.ReadKey();
    }
    public static void Main(string[] args)
    {
        var dt = new DateTime(2018, 04, 1);
        Console.WriteLine(dt);
       
        string month = dt.ToString("MMMM");
        Console.WriteLine(month);               //April

        month = dt.ToString("MMM");
        Console.WriteLine(month);              //Apr

        month = dt.ToString("MM");
        Console.WriteLine(month);             //04

        Console.ReadKey();
    }
话少心凉 2024-12-11 01:55:37

您的代码:

DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);

尝试将其更改为:

DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum);

当您打印日期/时间

打印datuMDokumenta.Text

your code:

DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);

try changing this to:

DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum);

and when u print the date/time

print datuMDokumenta.Text

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