Reputation: 1
This is my code.but value cannot inserted in database. it takes system datetime except selected value by drop down list.
string strDateOfBirth = ddlMonth.SelectedValue.ToString();
strDateOfBirth = strDateOfBirth + "/" + ddlBirthDate.SelectedValue.ToString();
strDateOfBirth = strDateOfBirth + "/" + ddlYear.SelectedValue.ToString();
//objVivah.BirthDate = DateTime.ParseExact(strDateOfBirth, "MM/dd/yyyy hh:mm", null);
objVivah.BirthDate = Convert.ToDateTime(strDateOfBirth);
// objVivah.BirthDate = Convert.ToString(strDateOfBirth);
Upvotes: 0
Views: 347
Reputation: 14781
To convert a String
to a DateTime
using the Convert.ToDateTime
function, the String
must be in a specific format. If your String
has a different format you need to convert it using DateTime.ParseExact function:
DateTime.ParseExact(strDateOfBirth, "MM/d/yyyy", CultureInfo.InvariantCulture);
Upvotes: 1
Reputation: 1503579
Well, I wouldn't create the string to start with - if you already have each part, you can parse those as integers (using int.Parse
) and then create a DateTime from that. Or for the drop-down lists, you may be able to avoid even having the string value to start with, which would be ideal. (Make the value associated with each item just an integer. This may not be feasible depending on what UI technology you're using - you haven't said whether it's WinForms, ASP.NET, WPF etc.)
Using DateTime.ParseExact
with an appropriate format string is the second best way to go, but I don't see any point in creating a string only to then parse it.
Upvotes: 0
Reputation: 9469
Try this:
objVivah.BirthDate = DateTime.ParseExact(strDateOfBirth, "MM/dd/yyyy", null);
You might want to have a look at TryParse as well.
Upvotes: 0