Cristian Boariu
Cristian Boariu

Reputation: 9621

why this parse from string to DateTime fails in C#?

I have a DateTime eventDate field in my Mysql table which I compose from the inputs when I insert it in db:

cmd.Parameters.Add("?eventDate", MySqlDbType.DateTime).Value = DateTime.ParseExact(txtEventDate.Text + " " + txtEventTime.Text,
                "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);

and is saved nice:

2011-05-05 10:20:00

Now, when I read it from DB I want to split it but it fails if I do like this:

txtEventDate.Text = DateTime.ParseExact(Reader.GetValue(7).ToString(), "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture).Date.ToShortDateString();
txtEventTime.Text = DateTime.ParseExact(Reader.GetValue(7).ToString(), "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture).TimeOfDay.ToString();

saying that:

String was not recognized as a valid DateTime.

Do you see any issue? I cannot figure out where I am wrong...

Upvotes: 2

Views: 686

Answers (3)

faester
faester

Reputation: 15086

It seems superfluous to convert it to a string and parse it as a datetime and this may introduce problems with enexpected date formats.

If you have a Datetime in the database you could also do

  txtEventDate.Text = Reader.GetDatetime(7).ToShortDateString();
  txtEventTime.Text = Reader.GetDatetime(7).TimeOfDay().ToString();

Upvotes: 4

Syjin
Syjin

Reputation: 2809

To format DateTime try something like this...

DateTime date = Reader.GetDateTime(7);
txtEventDate.Text = date.ToString("MM/dd/yyyy");
txtEventTime.Text = date.ToString("HH:mm:ss");

Upvotes: 1

Akram Shahda
Akram Shahda

Reputation: 14781

You have to provide the right format. That may be:

yyyy-dd-MM HH:mm:ss

Upvotes: 0

Related Questions