views:

75

answers:

5

Hi

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.

+2  A: 

Convert it to a DateTime then then use string.format to format it how you want.

    DateTime MyDateTime = Convertto.Date"01/12/2004 00:35:23",
   "dd/MM/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
    string.Format("The Date is:{0}", "yyyy/MM/dd",MyDateTime);
Ben Robinson
+1  A: 

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";
    }
}
Fredrik Mörk
That's great, thanks very much.
Rob Bowman
A: 
string testDate = "19/08/2010 06:19:30";
DateTime asDate = DateTime.ParseExact(testDate,
   "dd/MM/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(asDate.ToString("yyyy/MM/dd"));
BlueMonkMN
A: 

DataFormatString="{0:d}". You can give this property to your field. Write this in ASP page

I wasn't aware of the DataFormatString property - thank you.However, it seems DateFormatSting can only be used with a BoundColumn. My field is a TemplateField so that I can add a Validator to ensure that during Edit / Insert, the correct format it used.
Rob Bowman
A: 

Instead of using TextBox You may consider to use MaskedTextBox, then only thing that You do is to set the mask (format).

Read More about MaskedTextBox

Vash