我有一个 DetailsView,其中一个 TextBox 绑定(bind)到 DateTime 列。该列的值以“dd/mm/yyyy hh:mm:ss”格式显示。我需要它以“yyyy/mm/dd”格式显示。我认为最好的方法可能是在 DataBound 事件中格式化字符串。问题是,我似乎找不到将字符串格式化为日期的方法。 String.Format 不会这样做。如果我将字符串作为 DateTime,那么我可以使用 DateTime.Format 方法。我可以通过解析字符串的各种元素来创建日期时间变量,但我不禁认为一定有更简单的方法吗?
谢谢
罗布。
像这样的东西应该可以工作:
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";
}
}