简体   繁体   中英

How should I use the nullable type if it has a value

I have my Model:

[DataType(DataType.Date)]
public DateTime? Date1 { get; set; }

[DataType(DataType.Date)]
public DateTime? Date2 { get; set; }

[DataType(DataType.Date)]
public DateTime? Date3 { get; set; }

It's important for Data1 to Data3 to be DateTime?

My problem:

//Return right value
(model.Date1.ToString().AsDateTime().ToShortDateString() != "01.01.0001" ? model.Date1.ToString().AsDateTime().ToShortDateString() : "Is not known")
//Return bad value
(model.Date2.ToString().AsDateTime().ToShortDateString() != "01.01.0001" ? model.Date1.ToString().AsDateTime().ToShortDateString() : "Není známo")
//Return bad value
(model.Date3.ToString().AsDateTime().ToShortDateString() != "01.01.0001" ? model.Date3.ToString().AsDateTime().ToShortDateString() : "Is not known")

I dont know how or why but input is same but Date2 and Date3 returns bad value...

Thanks for any help

You can use the nullable types as follows.

model.Date1.HasValue ? model.Date1.Value.ToShortDateString() : "Unknown";

You can also compare with default datetime value by model.Date1.GetValueOrDefault() != default(DateTime) .

GetValueOrDefault will return default value if Date1 is null .

model.Date1.GetValueOrDefault() != default(DateTime) ? model.Date1.Value.ToShortDateString() : "Unknown";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM