danny taki
danny taki

Reputation: 450

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

Upvotes: 3

Views: 2377

Answers (4)

Soner Gönül
Soner Gönül

Reputation: 98750

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
}

Upvotes: 2

ehh
ehh

Reputation: 3480

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

Upvotes: 2

Joel Legaspi Enriquez
Joel Legaspi Enriquez

Reputation: 1236

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.

Upvotes: 1

DeshDeep Singh
DeshDeep Singh

Reputation: 1843

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);
      }

Upvotes: 1

Related Questions