将日期转换为字符串

时间:2012-03-14 00:54:24

标签: c# stored-procedures

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

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

                    });

2 个答案:

答案 0 :(得分:4)

假设reader.GetDateTime()返回一个c#DateTime对象,你需要做的就是调用ToString(),传入参数来格式化你喜欢的方式。

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

答案 1 :(得分:1)

将日期转换为字符串的最佳方法是不要这样做。

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

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

相关问题