0

I have two string variables. The first one is from a label (This date will be subject to changed dependant on a datetimepicker). The second one is a time that is selected in a combo box. The format is in this example -

lblActualDate.Text - 11 June 2015
comboStartTime.Text - 12.00AM

I am getting errors about the strings not being in the correct format to convert to date time.

My aim is to make an instance with the values from a form Here is my code -

private void btnSave_Click(object sender, EventArgs e)
    {
        string dateString = lblActualDate.Text + " " + comboStartTime.SelectedItem;

        DateTime startTime = DateTime.ParseExact(dateString, "dd MMMM yyyy hh.mmtt", CultureInfo.InvariantCulture);

        int length = int.Parse(comboLength.SelectedText);
        string description = txtBoxSubject.Text;
        string location = txtBoxLocation.Text;

        Appointment newAppointment = new Appointment(startTime, length, description, location);
        Appointments appointments = new Appointments();

        appointments.Add(newAppointment);
        appointments.Save();

        txtBoxLocation.Clear();
        txtBoxSubject.Clear();
        Dispose();
    }
Pete
  • 83
  • 1
  • 7
  • 1
    Consider using [DateTime.TryParse](https://msdn.microsoft.com/en-us/library/system.datetime.tryparse%28v=vs.110%29.aspx), or [DateTime.Parse](https://msdn.microsoft.com/en-us/library/1k1skd40(v=vs.110).aspx). – Jason Evans Jun 11 '15 at 11:44
  • You need to convert the string variables into a DateTime type – Harry Jun 11 '15 at 11:45
  • 2
    take a look at [`DateTime.TryParseExact`](https://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact%28v=vs.110%29.aspx) method. – Zohar Peled Jun 11 '15 at 11:45
  • Aside from already existing and correct answer, remember to add a whitespace between your strings when adding them OR properly change your custom date/time format if you're using one. – S_F Jun 11 '15 at 11:46

2 Answers2

4

Convert.ToDateTime uses standard date and time formats of your CurrentCulture. That means your string format doesn't match one of these formats.

You can use custom date and time formats to parse your string like;

string s = "11 June 201512.00AM";
DateTime startTime = DateTime.ParseExact(s, "dd MMMM yyyyhh.mmtt", 
                                            CultureInfo.InvariantCulture);

Also consider to put a white space between your date and time part.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Thnak you. Do I need a namespace to use 'Dump()'. It is showing an error – Pete Jun 11 '15 at 12:01
  • @Pete [`Dump`](http://stackoverflow.com/questions/3555317/linqpad-extension-methods) is an extension method for [LINQPad](https://www.linqpad.net/). You definitly **don't** need to use it. Sorry about the confusion. Deleted that part. Generally, I use this tool for Stack Overflow questions to generate code examples. – Soner Gönül Jun 11 '15 at 12:04
  • I am a little confused as I am not writing to a console. I need to store the date and time in a DateTime variable – Pete Jun 11 '15 at 12:05
  • Does there not need need to be any code in the brackets? – Pete Jun 11 '15 at 12:10
  • It isn't working i'm afraid. "No overload for method takes 3 arguments - – Pete Jun 11 '15 at 12:15
  • string dateString = lblActualDate.Text + " " + comboStartTime.SelectedText; DateTime startTime = DateTime.TryParseExact(dateString, "dd mmmm yyyy hh.mmtt", CultureInfo.InvariantCulture); – Pete Jun 11 '15 at 12:16
  • @Pete Sorry, it should be `ParseExact` not `TryParseExact`. Updated my answer. – Soner Gönül Jun 11 '15 at 12:32
  • Thank you for your time but unfortunately I still get an exception thrown. There must be an error somewhere else in the code – Pete Jun 11 '15 at 12:46
  • @Pete Maybe. You can debug your code and see exact line throws any exception. – Soner Gönül Jun 11 '15 at 12:46
  • Yes. It was that line actually. Am I using the correct code to get the combobox string? – Pete Jun 11 '15 at 13:02
  • It is still saying it is not the correct format. There variables in the debug say this - dateString - "11 June 2015 05.00AM" startTime - {11/06/2015 5:00:00 AM} – Pete Jun 11 '15 at 13:18
  • @Pete If your hour part has leading zero for single digit, use `hh` specifier instead. – Soner Gönül Jun 11 '15 at 13:46
  • @Pete Oh yes, it is. I think you need a white space between `yyyy` and `hh` part since you want to parse as `...2015 05...`. – Soner Gönül Jun 11 '15 at 14:00
  • string dateString = lblActualDate.Text + " " + comboStartTime.SelectedItem; DateTime startTime = DateTime.ParseExact(dateString, "dd Mmmm yyyy hh.mmTT", CultureInfo.InvariantCulture); here is my code. I added the white space earlier but still get the exception unfortunatly – Pete Jun 11 '15 at 14:01
  • @Pete Look at your format and mine. Are they equal? You should use `"dd MMMM yyyy hh.mmtt"` format. – Soner Gönül Jun 11 '15 at 14:03
0

Most likely you've got some combinations with one digit, and others with two digits in either the day or hour portions of your date/time.

You can allow all the possibilities by building up an array of allowable formats and passing that to ParseExact:

string[] formats = { "d MMMM yyyy h.mmtt", "d MMMM yyyy hh.mmtt", "dd MMMM yyyy h.mmtt", "dd MMMM yyyy hh.mmtt" };
DateTime startTime = DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • Thank you. That works now. I have a problem on the next line --- int length = int.Parse(comboLength.SelectedItem); Select item should be a string number ie, 270. I would have thought this would be straight forward but apparently not – Pete Jun 11 '15 at 15:00
  • Perhaps there is nothing selected?...or you've got a value in the combo that is not actually an integer. Wrap the `Parse` call in a Try/Catch block, or switch to `TryParse`. Either way, figure out what value(s) are causing the errors and adjust accordingly... – Idle_Mind Jun 11 '15 at 15:04