日期时间为空的年份
本文关键字:时间 日期 | 更新日期: 2023-09-27 18:29:40
如何计算nullable
日期中的年份?
partial void AgeAtDiagnosis_Compute(ref int result)
{
// Set result to the desired field value
result = DateofDiagnosis.Year - DateofBirth.Year;
if (DateofBirth > DateofDiagnosis.AddYears(-result))
{
result--;
}
}
错误为:
'System.Nullable<System.DateTime>' does not contain a definition for 'Year' and no
extension method 'Year' accepting a first argument of
type 'System.Nullable<System.DateTime>' could be found (are you missing a using
directive or an assembly reference?)
用DateofDiagnosis.Value.Year
替换DateofDiagnosis.Year
并且首先检查DateofDiagnosis.HasValue
以断言它不是空的。
我会这样写代码:
private bool TryCalculateAgeAtDiagnosis( DateTime? dateOfDiagnosis,
DateTime? dateOfBirth,
out int ageInYears)
{
if (!dateOfDiagnosis.HasValue || !dateOfBirth.HasValue)
{
ageInYears = default;
return false;
}
ageInYears = dateOfDiagnosis.Value.Year - dateOfBirth.Value.Year;
if (dateOfBirth > dateOfDiagnosis.Value.AddYears(-ageInYears))
{
ageInYears--;
}
return true;
}
首先检查它是否有Value
:
if (date.HasValue == true)
{
//date.Value.Year;
}
使用nullableDateTime.Value.Year
。
您的代码可能是这样的
partial void AgeAtDiagnosis_Compute(ref int result)
{
if(DateofDiagnosis.HasValue && DateofBirth.HasValue)
{
// Set result to the desired field value
result = DateofDiagnosis.Value.Year - DateofBirth.Value.Year;
if (DateofBirth > DateofDiagnosis.Value.AddYears(-result))
{
result--;
}
}
}