繁体   English   中英

C#字符串未被识别为有效的DateTime

[英]C# String was not recognized as a valid DateTime

dateString为以下dateString但在更早的时间内运行了另一个时间时抛出错误,不确定为什么它现在不起作用。

 string dateString = "Jul 24, 2015 4:03:51 PM PDT";
            string format = "MMM dd, yyyy h:mm:ss tt PDT";
            CultureInfo provider = CultureInfo.InvariantCulture;
            DateTime time = DateTime.ParseExact(dateString, format, provider);
            Console.WriteLine(time);

编辑后的代码:最后两行之一抛出错误,有时将执行第一个DateTime,但不执行第二个。 提示窗口首先会要求最早的日期和时间,即:太平洋夏令时2015年7月24日上午6:26:15。 然后是另一个提示,提示最新的DateTime是:PDT 2015年7月24日下午4:03:51

string afterpromptvalue = Prompt.ShowDialog("Enter earliest Date and Time", "Unshipped Orders");
            string beforepromptvalue = Prompt.ShowDialog("Enter latest Date and Time", "Unshipped Orders");

            string format = "MMM dd, yyyy h:mm:ss tt PDT";
            CultureInfo provider = CultureInfo.InvariantCulture;

            DateTime createdAfter = DateTime.ParseExact(afterpromptvalue, format, provider);
            DateTime createdBefore = DateTime.ParseExact(beforepromptvalue, format, provider);

再次编辑:我想放入提示对话框代码,因为这可能是问题所在。

public static class Prompt
{
    public static string ShowDialog(string text, string caption)
    {
        Form prompt = new Form();
        prompt.Width = 500;
        prompt.Height = 150;
        prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
        prompt.Text = caption;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        Label textLabel = new Label() { Left = 50, Top=20, Text=text };
        TextBox textBox = new TextBox() { Left = 50, Top=50, Width=400 };
        Button confirmation = new Button() { Text = "Ok", Left=350, Width=100, Top=70, DialogResult = DialogResult.OK };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.AcceptButton = confirmation;

        return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
    }
}

您的代码在我的机器上正常运行,没有任何错误。 尝试在其他计算机或其他解决方案中执行它。 如果可行,则意味着您的解决方案需要清洁和构建。 如果不起作用,则意味着您可能缺少必需的参考-

using System;
using System.Globalization;

日期解析的一个常见错误是使用dd而不是d 使用dd ,将传递24的值,但不会传递9 后者必须改为09 如果你使用一个单一的d ,然而,然后909 ,和24都会被允许。

暂无
暂无

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

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