I have a column of Datetime values in a table. I am using a LINQ query in a Controller to create model objects, where I am trying to perform a calculation to return the amount of days since the date value until now. The result updates another string variable depending on the result's value.
This is the LINQ query
public ActionResult Index()
{
var result = from a in db.area
join c in db.sample
on a.location_id equals c.location_id into samples
let sample = samples.OrderByDescending(c => c.date_sampled).FirstOrDefault()
select new StatusModel
{
location_name = a.location_name,
latitude = a.latitude,
longitude = a.longitude,
status = sample.sample_status,
sampDate = sample.sample_date ?? DateTime.Now
};
return View(result);
}
And this is the method and constructor from my StatusModel to perform the calculation.
public int difference;
public StatusModel()
{
setStatus();
}
public void setStatus()
{
DateTime oldDate = sampDate;
DateTime newDate = DateTime.Now;
TimeSpan ts = newDate - oldDate;
difference = ts.Days;
}
The setStatus method works fine when I manually type in a date, i.e. if I set
DateTime oldDate = new DateTime(2016,2,9);
It returns as expected. However using the sampDate variable, it returns '736047' as the number of days for everything! The date in my database is set like '2016-01-04', when I run my project all dates in the Views are converted to MM-DD-YYYY, perhaps this is the problem.