Reputation: 71
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.
Upvotes: 3
Views: 27065
Reputation: 2143
At the Database Level the column is declared as DATE
PaymentClearingDate DATE NULL
To avoid the error
unable to cast object of type 'System.DateOnly' to type 'System.IConvertible'.
We do ToString() on the PaymentClearingDate property and then Convert.ToDateTime() as shown below.
PAYMENT_CLEARING_DATE = Convert.ToDateTime(payment.PaymentClearingDate.ToString())
Upvotes: 0
Reputation: 54887
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.
Upvotes: 1
Reputation: 1585
You should try this
DateTime.ParseExact("20-Oct-2012", "dd-MMM-yyyy", null).ToString("yyyy/mm/dd")
For further reading on formats Check This
Upvotes: 6
Reputation: 14282
You could try this instead :
Convert.ToDateTime("20-Oct-2012").ToString("yyyy/MM/dd")
Hope this will help !!
Upvotes: 0