0

I have a string like this and I want to convert it to DateTime format(MM/dd/yyyyTHH:mm:ss). but it fails, Please let me know where I'm wrong.

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

string stime = "4/17/2014T12:00:00";
DateTime dt = DateTime.ParseExact(stime, "MM/dd/yyyyTHH:mm:ss", CultureInfo.InvariantCulture);

This is the code, how I'm setting this string:

string startHH = DropDownList1.SelectedItem.Text;
string startMM = DropDownList2.SelectedItem.Text;
string startSS = DropDownList3.SelectedItem.Text;
string starttime = startHH + ":" + startMM + ":" + startSS;
string stime = StartDateTextBox.Text + "T" + starttime;

Getting this exception

String was not recognized as a valid DateTime.
2
  • 1
    Since you parse exact then MM is expecting a two digit month where as you string only has 4. '04/17...' would had worked Commented Apr 2, 2014 at 19:03
  • Why using the ISO 8601 T delimiter with incompatible date format ? This is rather misleading. Commented Apr 2, 2014 at 19:09

3 Answers 3

2

You wrote MM in your format string, which means that you need a two digit month. If you want a one digit month, just use M.

DateTime dt = DateTime.ParseExact(stime, "M/dd/yyyyTHH:mm:ss", CultureInfo.InvariantCulture);

The other solution is to change your string to match your format.

string stime = "04/17/2014T12:00:00";
DateTime dt = DateTime.ParseExact(stime, "MM/dd/yyyyTHH:mm:ss", CultureInfo.InvariantCulture);

The key to this is remembering you're doing parse exact. Therefore, you must exactly match your string with your format.

Sign up to request clarification or add additional context in comments.

Comments

1

Problem : in your date string 4/17/2014T12:00:00 you have only single digit Month value (4) but in your DateFormat string you mentione double MM

Solution : you should specify single M instead of double MM

Try This:

DateTime dt = DateTime.ParseExact(stime, "M/dd/yyyyTHH:mm:ss", 
                              CultureInfo.InvariantCulture);

Comments

0

Pay attention your date string contains only 1 digit for month but your patters defines MM.
So either use month 04 or change pattern to M.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.