2010-08-19 108 views
2

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

谢谢

Rob。

回答

5

像这样应该工作:

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"; 
    } 
} 
+0

太好了,非常感谢。 – 2010-08-19 12:52:43

1

它转换为datetime,然后再使用的String.Format来格式化你想怎么。

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); 
1
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")); 
0

DataFormatString = “{0:d}”。你可以把这个属性给你的领域。写在ASP页

+0

我不知道DataFormatString属性 - 谢谢。 但是,它似乎DateFormatSting只能用于BoundColumn。我的字段是一个TemplateField,因此我可以添加一个验证器以确保在编辑/插入过程中使用了正确的格式。 – 2010-08-19 12:55:14