简体   繁体   中英

convert date string to datetime

I have date string in format dd-MMM-yyyy and want to convert this to datetime , when I use below code

DateTime.ParseExact("20-Oct-2012", "yyyy-MM-dd HH:mm tt", null) 

it causing an error

String was not recognized as a valid DateTime.

When I modify above code

DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null) 

then I got date time in format ( mm/dd/yyyy ) : 10/20/2012 12:00:00 AM

But I need it should be converted in yyyy/mm/dd format. Please help me in this regard.

You should try this

DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null).ToString("yyyy/mm/dd")

For further reading on formats Check This

You need to distinguish between two separate concerns: that of parsing your original string into an abstract DateTime representation, and that of converting the latter back into another string representation.

In your code, you're only tackling the former, and relying on the implicit ToString() method call (which uses the system's current locale) to convert it back to string. If you want to control the output format, you need to specify it explicitly:

// Convert from string in "dd-MMM-yyyy" format to DateTime.
DateTime dt = DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null);

// Convert from DateTime to string in "yyyy/MM/dd" format.
string str = dt.ToString("yyyy/MM/dd");

Also note that the mm format specifier represents minutes; months are represented by MM .

Edit : 'Converted date contain value "10/20/2012 12:00:00 AM".' Be careful what you mean by that. The constructed DateTime value contains an abstract representation of the parsed date and time that is independent of any format.

However, in order to display it, you need to convert it back into some string representation. When you view the variable in the debugger (as you're presumably doing), Visual Studio automatically calls the parameterless ToString() method on the DateTime , which renders the date and time under the current culture (which, in your case, assumes the US culture).

To alter this behaviour such that it renders the date and time under a custom format, you need to explicitly call the ToString(string) overload (or one of the other overloads), as I've shown in the example above.

You could try this instead :

Convert.ToDateTime("20-Oct-2012").ToString("yyyy/MM/dd")

Hope this will help !!

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