2

i have date stored in a string format as follows: "2014-03-12" im passing this to a database which accepts the date as datetime. im converting the string date to datetime format as follows:

DateTime StartDates = Convert.ToDateTime(StartDate);

but the time gets appended along with the date as "2014-03-12 12:00:00:00"

can anyone tel me how to send only the date leaving out the time. i want the final date to be still in datetime format only but with time part cut off

2 Answers 2

5

DateTime is irrespective of the format. Formatting is only useful for presentation purpose. A DateTime object will have a Date part and Time part. When you try parsing your string "2014-03-12", it doesn't have a Time part, so in the parsed object, Time is set to 00:00:00.

If you just want to to display date then you can use DateTime.ToShortDateString method or use a custom format like:

string formattedDateString = StartDates.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
Sign up to request clarification or add additional context in comments.

3 Comments

I would strongly advise against DateTime.ToShortDateString, but other than that this should be the accepted answer.
@Crono, ToShortDateString is useful when you want to show only Date part for any culture, like for US culture it would show MM/dd/yyyy and for British culture it will show dd/MM/yyyy. Could you please specify why it shouldn't be used. (in OPs case it can't be used since OP is targeting a custom format for displaying)
I'm so sorry, it seems my brain decided to completely ignore that obvious If you just want to display date right before. My bad.
0

If you're happy with the date part, you may simply return the Date property of the DateTime conversion result:

DateTime StartDates = Convert.ToDateTime(StartDate).Date;

I should mention that using Convert.ToDateTime puts you at the mercy of the process current culture date format though, so you probably want to use the ParseExact or ToString method like the other answers suggests, with the appropriate format and culture instance.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.