Question

I am getting date from a dropdown. The date format that is coming in weekStartDate is 12/05/2014 12:00:00 AM. I want it to be as 2014/05/12 12:00:00 AM

DateTime weekStartDate = Convert.ToDateTime(DrpDwnGetPayPeriod.SelectedValue);

The dropdown has values as 05 May 2014 , 12 May 2014 . When I try to parse it , I get error as String was not recognized as a valid DateTime. I tried following:

DateTime weekStartDate = DateTime.ParseExact(DrpDwnGetPayPeriod.SelectedValue, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Was it helpful?

Solution

The dropdown has values as 05 May 2014 , 12 May 2014 . When I try to parse it , I get error as String was not recognized as a valid DateTime

So these are entries in the DropDownList:

05 May 2014
12 May 2014
21 Apr 2014

and you want to parse it to a real DateTime.

Then you can use DateTime.ParseExact:

// presuming "21 Apr 2014" is DrpDwnGetPayPeriod.SelectedValue
DateTime weekStartDate = DateTime.ParseExact("21 Apr 2014", "dd MMM yyyy", CultureInfo.InvariantCulture);

Since you're using three letter abbreviations for month names you need to use MMM.

MSDN: Custom Date and Time Format Strings

OTHER TIPS

Use the standard format "G":

weekStartDate.ToString("G"); //G: 12/5/2014 12:00:00 AM 

http://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx

Are you just trying to change the formatting on weekStartDate? You would just need to do something along these lines:

weekStartDate.ToString("yyyy/MM/dd hh:mm tt");

Here's an example.

It's a little unclear in your question. But I'm going to assume you want to know "how do I convert a string in a certain format into a DateTime object?" If that's not your question, please clarify and realize that you need to make your question clearer in the beginning.

Learn to use DateTime.ParseExact. And use the format strings. That gives us...

DateTime weekStartDate = DateTime.ParseExact(DrpDwnGetPayPeriod.SelectedValue, "yyyy-MM-dd hh:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture);

Note, you may want to make use of DateTime.TryParseExact. That will allow you to handle values that don't match the specified format.

Click this link for custom date time formatting

I think you have to use a function like this:

DateTime.Today.ToString("YY/MM/DD HH:MM:SS TT")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top