Reputation: 855
How can I convert a datetime object to the format yyyy/MM/dd? I am trying this:
DateTime selectedDate =Convert.ToDateTime( Calendar1.SelectedDate.ToShortDateString());
selectedDate = DateTime.ParseExact(selectedDate, "yyyy/MM/dd", CultureInfo.InvariantCulture);
But I get the following errors:
The best overloaded method match for 'System.DateTime.ParseExact(string, string, System.IFormatProvider)' has some invalid arguments
or
Argument '1': cannot convert from 'System.DateTime' to 'string'
Upvotes: 1
Views: 17659
Reputation: 3253
ParseExact converts a string to a datetime, so
selectedDate = DateTime.ParseExact("2012/02/29", "yyyy/MM/dd", CultureInfo.InvariantCulture);
would work. Not sure why you want to convert a datetime to a datetime??
Upvotes: 0
Reputation: 62544
Date format makes sense when you are going to convert it to string or display in UI/somewhere else.
If Calendar1.SelectedDate
is of DateTime
type:
string date = Calendar1.SelectedDate.ToString(
"yyyy/MM/dd",
CultureInfo.InvariantCulture);
If Calendar1.SelectedDate
is of string
type:
string date = DateTime.ParseExact(
Calendar1.SelectedDate,
"yyyy/MM/dd",
CultureInfo.InvariantCulture);
Upvotes: 0
Reputation: 499362
A DateTime
does not have an inherent format - only an internal representation.
Formatting comes into play when you want to display the value of the DateTime
instance:
string formatted = DateTime.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
The above formatted
string will contain the values of the DateTime
instance in the required format.
Upvotes: 4