当值为 null 时将日期时间显示为“00000000”

Displaying date time as "00000000" when value is null

我正在编写一个小型控制台应用程序并从数据库中检索数据,并且当数据库中保存的值为空时需要将日期时间数据显示为“00000000”。

我试过了

string temp = v.CompetentDate != null ? v.CompetentDate : "00000000";
DateTime competentdate = DateTime.Parse(temp);
v.CompetentDate = competentdate.ToString("ddMMyyyy");

但得到一个异常 String was not recognised as a valid DateTime

如果数据库中的值为空,我如何才能获得“00000000”的值。

为什么要将字符串转换为日期时间然后再转换回字符串?只需设置字符串值

v.CompetentDate = v.CompetentDate ?? "00000000";

您可以这样使用 DateTime.TryParse Method

DateTime temp;
v.CompetentDate = DateTime.TryParse(competentdate,out temp)?
                  temp.ToString("ddMMyyyy"):
                  "00000000";

试一试

string temp = v.CompetentDate != null ? v.CompetentDate : "00000000";
 DateTime competentdate = DateTime.Parse(temp);
v.CompetentDate = competentdate.ToString("dd,mm,yyyy");

DateTime.MinValue.ToString("ddMMyyyy")returns 01010001 不是 00000000。这就是为什么如果你尝试 DateTime.Parse("00000000");.

你会得到那个例外

相反,你可能想要这个(即使我会使用 01010001 而不是 00000000):

v.CompetentDate = v.CompetentDate != null 
    ? DateTime.Parse(v.CompetentDate).ToString("ddMMyyyy") 
    : "00000000";

顺便说一句,你为什么不用 DateTime 代替 CompetentDate