2012-03-14 188 views
1

我从存储过程获取数据,并想知道哪个是将DateTime(或日期)转换为字符串的最简单方法?将日期转换为字符串

recipes.Add(new Recipe 
        { 
         RecipeId = reader.GetInt32(recipeIdIndex), 
         Name = reader.GetString(nameIndex), 
         Date = reader.GetDateTime(dateIndex), //Date is a string 

        }); 
+2

你有什么试过?除了明显的.ToString()之外,还有其他选项。我会提出这样的问题:“为什么你只想将日期转换成食谱类中的字符串?”我会让它保留一个DateTime,直到它需要显示。 – 2012-03-14 00:56:44

+0

当我使日期成为日期时间时,我收到消息“Unable to cast object of type'System.Byte'to type'System.String'。”食谱是一个列表,我错过了什么?我无法得到它的工作。 – 2012-03-14 01:17:41

回答

1

将日期转换为字符串的最佳方法是完全没有这样做。

如果您必须将日期时间存储为字符串,请使用DateTime.ToString("o")或ISO8601格式.ToString("yyyy-MM-dd HH:mm:ss.ttt")作为SynXsiS建议的格式。

确保您知道日期是在本地还是UTC时间 - 您可能需要在显示给用户之前调整值。

4

假设reader.GetDateTime()函数返回一个C#DateTime对象,所有你需要做的就是调用toString()就可以在参数传递,你怎么样进行格式化。

reader.GetDateTime(dateIndex).ToString("yyyy-MM-dd HH:mm:ss.ttt")