简体   繁体   中英

Parse DateTime from Dropdown Selected Value

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);

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")

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM