我在MVC项目中有一个存储活动的模型。我需要显示开始时间和结束时间之间的时差。 这是我的模型课:
[Table("DailyCrewActivity")]
public partial class DailyCrewActivity
{
[Key]
public int id { get; set; }
[Display(Name = "Crew Name")]
[ForeignKey("DailyCrew")]
public int daily_crew_id { get; set; }
[Display(Name = "Task Number")]
[ForeignKey("ContractTask")]
public int contract_task_id { get; set; }
[Display(Name = "Activity Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime activity_date { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Activity Code")]
public string activity_code { get; set; }
[Display(Name = "Start Time")]
[DisplayFormat(DataFormatString = "{0:hh:mm}")]
public string activity_start { get; set; }
[Display(Name = "End Time")]
[DisplayFormat(DataFormatString = "{0:hh:mm}")]
public string activity_end { get; set; }
[NotMapped]
[Display(Name = "Hours")]
[DisplayFormat(DataFormatString = "{0:#.##}")]
public decimal ElapsedTime
{
get
{
decimal duration = 0;
if (String.IsNullOrEmpty(activity_start) && String.IsNullOrEmpty(activity_end))
{
TimeSpan spanStart;
TimeSpan spanEnd;
if (TimeSpan.TryParse(activity_start, out spanStart) && TimeSpan.TryParse(activity_end, out spanEnd))
{
duration = Convert.ToDecimal(spanEnd - spanStart);
}
}
return duration;
}
}
public DailyCrew DailyCrew { get; set; }
public ContractTask ContractTask { get; set; }
}
我没有将计算返回到ElapsedTime。是因为我将时间存储在字符串中,然后将其解析为TimeSpan吗? 我不确定这是怎么回事。
谢谢
瑞安
答案 0 :(得分:0)
您正在检查两个值是否都为null,这不会给您任何帮助。您需要改为同时检查两个都不为空/空:
if (!String.IsNullOrEmpty(activity_start) && !String.IsNullOrEmpty(activity_end))
{
...
}