Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Format String as Date [closed]

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.

like image 899
Rob Bowman Avatar asked Dec 22 '22 00:12

Rob Bowman


1 Answers

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";
    }
}
like image 193
Fredrik Mörk Avatar answered Jan 07 '23 18:01

Fredrik Mörk