Our Man in Bananas
Our Man in Bananas

Reputation: 5981

String to datetime conversion issue with DatePicker

I am reading strings from an XML config file in elements then converting them to datetimes to go in a datetime picker control.

The values are in the XML file are:

<config>
  <Triggers>
    <CalendarTrigger>
      <Start>2012-07-02T18:00:00</Start>
      <Next>2013-10-22T10:40:00</Next>
      <Last>2013-10-01T18:00:00</Last>
      <Result>Success</Result>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        ... and so on...

I am using the below code to convert the string values into dates for a datetimepicker control:

CalendarTrigger[0] = (result.Element("Next").Value != "") ? Convert.ToDateTime(result.Element("Next").Value).ToString("dd/MM/yyyy HH:mm:ss") : DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
dScanDate.Value = Convert.ToDateTime(CalendarTrigger[0]);
dScanTime.Value = Convert.ToDateTime(CalendarTrigger[0]);

unfortunately even though the code is reading the values correctly into CalendarTrigger[0] (CalendarTrigger[0] = "22/10/2013 10:40:00") I am getting a String was not recognized as a valid DateTime. error.

What am I doing wrong please?

Upvotes: 0

Views: 7563

Answers (3)

Our Man in Bananas
Our Man in Bananas

Reputation: 5981

I found the answer, I was usiong an incorrect format for datetime conversion

it should be

CalendarTrigger[0] = (result.Element("Next").Value != "") ? Convert.ToDateTime(result.Element("Next").Value).ToString("MM/dd/yyyy HH:mm:ss") :DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");

Upvotes: 0

Carbine
Carbine

Reputation: 7903

Try

string timeString = "23/10/2013 10:40:00";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(timeString, "dd/MM/yyyy HH:mm:ss", culture);

or just using InvariantCulture

string timeString = "23/10/2013 10:40:00"
DateTime dateVal = DateTime.ParseExact(timeString, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Upvotes: 1

Nickon
Nickon

Reputation: 10156

Maybe, try to set a custom format for your DateTimePicker:

dateTimePicker.CustomFormat = "dd/MM/yyyy HH:mm:ss";
dateTimePicker.Format = DateTimePickerFormat.Custom;

Upvotes: 1

Related Questions