简体   繁体   中英

String was not recognized as a valid DateTime using DateTime.ParseExact C#

Thought I solved this issue, but I am still having a problem with it. Trying to run this code to parse a Date and Time from user input in a prompt, but evertime I try to DateTime.ParseExact I get an error invalid format. Sample Date : Jul 24, 2015 9:08:19 PM PDT Jul 26, 2015 2:13:54 PM PDT

        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`

Here's the code for the prompt box:

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

The input you gave is not the same as expected , you enter minutes with 2 digits instead of one. Since your expected time format is h:m:s, you cannot provide 9:08:19, but you need to enter 9:8:19.

See for correct format usage msdn link:

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Considering of your both string, you just need to use mm specifier instead of m specifier since your single digit minutes has leading zeros .

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

As an example;

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
}

and

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
}

try this: problem might be you are converting to date time with specific format but not giving the same as input:

dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
      format = "ddd dd MMM yyyy hh:mm:ss tt zzz";
      try {
         result = DateTime.ParseExact(dateString, format, provider);
         Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("{0} is not in the correct format.", dateString);
      }

A quick check on your code via Console program and it reveals to my PC that it is working properly:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Globalization;

    namespace DateTimeConvert
    {
        class Program
        {
            static void Main(string[] args)
            {

                var text1 = "Jul 24, 2015 9:08:19 PM PDT";
                var text2 = "Jul 26, 2015 2:13:54 PM PDT";

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

                var date1 = DateTime.ParseExact(text1, format, CultureInfo.InvariantCulture);
                Console.WriteLine(date1);

                var date2 = DateTime.ParseExact(text2, format, CultureInfo.InvariantCulture);
                Console.WriteLine(date2);

                Console.ReadLine();
            }
        }
    }

Is it possible for you to run the above code and see if it still throws the same exception? There might be some other areas that needs to be checked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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