I have a DetailsView with a TextBox bound to a DateTime column. The value of the column is presented in the format "dd/mm/yyyy hh:mm:ss". I need it to be displayed in the format "yyyy/mm/dd". I had though that the best way may be to format the string in the DataBound event. Problem is, I can't seem to find a way to format the string as a date. The String.Format won't do it. If I had the string as a DateTime then I could use the DateTime.Format method. I could create a datetime variable by parsing the various elements of the string but I can't help but think there must be an easier way?
Thanks
Rob.
Something like this should work:
public static string GetDateString(string date)
{
DateTime theDate;
if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
{
// the string was successfully parsed into theDate
return theDate.ToString("yyyy'/'MM'/'dd");
}
else
{
// the parsing failed, return some sensible default value
return "Couldn't read the date";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With