数据库中的日期时间空值



正如我上面的标题,我在数据库中得到了一个DateTime数据类型的表,它是空值。我得到了我正在使用的这一行代码,但我不知道为什么它会返回12:00

string FitaCorIn1 = Convert.ToDateTime(req.FACorrectionIn1).ToString("hh:mm") == null ? "00:00" : Convert.ToDateTime(req.FAIn1).ToString("hh:mm");
string FitaCorOut1 = Convert.ToDateTime(req.FACorrectionOut1).ToString("hh:mm") == null ? "00:00" : Convert.ToDateTime(req.FAIn1).ToString("hh:mm");

因此,正如您在我的代码中看到的那样,如果日期时间的值为空,我想显示00:00,如果它不为空,它将显示当前值。

注意

12小时格式

您应该在转换它们之前检查 null,否则您可能会从转换方法中获得异常。(根据评论)似乎FACorrectionIn1是日期时间类型,因此您必须检查将它们与DateTime.MinValue进行比较,如果它是可为空的日期时间,您也可以检查空。

为什么12:00即使数据库中的值是 零

同样的原因FACorrectionIn1是一个 DateTime 对象,因此它不会为 null,因此检查 null 的条件变为 false,因为它的默认值为01/01/0001 00:00:00。因此,当您使用.ToString("hh:mm")格式化它们时,您会得到12:00.所以你必须这样做:

string FitaCorIn1 = req.FACorrectionIn1 == DateTime.MinValue ? "00:00" : 
Convert.ToDateTime(req.FAIn1).ToString("hh:mm");

如果您使用解析来代替Convert.To..那就太好

您应该使用HH:mm格式。

Convert.ToDateTime(req.FAIn1).ToString("HH:mm");

我现在明白了..感谢spencer7593.这是我的代码现在的样子。

string FitaCorIn1 = req.FACorrectionIn1 == null ? "00:00" : Convert.ToDateTime(req.FACorrectionIn1).ToString("hh:mm");
string FitaCorOut1 = req.FACorrectionOut1 == null ? "00:00" : Convert.ToDateTime(req.FACorrectionOut1).ToString("hh:mm");

最新更新