gpt4 book ai didi

c# - 使用 DateTime.ParseExact C# 未将字符串识别为有效的 DateTime

转载 作者:行者123 更新时间:2023-11-30 14:27:45 24 4
gpt4 key购买 nike

以为我解决了这个问题,但我仍然遇到问题。尝试运行此代码以在提示中从用户输入中解析日期和时间,但每次我尝试 DateTime.ParseExact 时都会收到错误格式无效。样本日期:太平洋夏令时间 2015 年 7 月 24 日晚上 9:08:19太平洋夏令时间 2015 年 7 月 26 日下午 2:13:54

        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 d, yyyy h:m:s tt PDT";
CultureInfo provider = CultureInfo.InvariantCulture;

DateTime createdAfter = DateTime.ParseExact(afterpromptvalue, format, provider);
DateTime createdBefore = DateTime.ParseExact(beforepromptvalue, format, provider);`enter code here`

提示框代码如下:

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 : "";
}

最佳答案

考虑到你的两个字符串,你只需要使用 mm specifier而不是 m specifier因为你的个位数分钟有 leading zeros .

string format = "MMM d, yyyy h:mm:s tt PDT";

举个例子;

string s = "Jul 24, 2015 9:08:19 PM PDT";
DateTime dt;
if(DateTime.TryParseExact(s, "MMM d, yyyy h:mm:s tt PDT", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// 24.07.2015 21:08:19
}

string s = "Jul 26, 2015 2:13:54 PM PDT";
DateTime dt;
if(DateTime.TryParseExact(s, "MMM d, yyyy h:mm:s tt PDT", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// 26.07.2015 14:13:54
}

关于c# - 使用 DateTime.ParseExact C# 未将字符串识别为有效的 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31645026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com