C#将字符串格式化为日期

Rob*_*man 2 c# datetime string-formatting

我有一个DetailsView与TextBox绑定到DateTime列.列的值以"dd/mm/yyyy hh:mm:ss"格式显示.我需要它以"yyyy/mm/dd"格式显示.虽然我有最好的方法可能是格式化DataBound事件中的字符串.问题是,我似乎无法找到将字符串格式化为日期的方法.String.Format不会这样做.如果我将字符串作为DateTime,那么我可以使用DateTime.Format方法.我可以通过解析字符串的各种元素来创建一个datetime变量,但我不禁想到必须有一个更简单的方法吗?

谢谢

抢.

Fre*_*örk 7

这样的事情应该有效:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)