I have 2 fields in a table, one for the date as DateTime, one for the time as Timespan.
I really want to construct a complete DateTime value with these two values, but I'm really struggling. This is what I got:
PostThr postThr = _context.PostThrs.FirstOrDefault(m => m.ThrZero == zero && m.ThrText == "SCHEDULED START-"); //this is the row with the specifc value
DateTime startDate = postThr.ThrDate; //this is the dateTime col
TimeSpan startTime = postThr.ThrTime; //this is the timeSpan col
string dateString = string.Concat(startDate.ToString("yyyyMMdd"), "T", startTime.ToString());
DateTime trafficDate = DateTime.ParseExact(dateString, "yyyyMMddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
CodePudding user response:
You can add a TimeSpan
to a DateTime
directly using addition operator or the Add method:
DateTime trafficDate=postThr.ThrDate.Date postThr.ThrTime;
Even if this wasn't possible, there would be no reason to convert the DateTime and TimeSpan values to strings, you could use one of the DateTime constructors to pass each element directly.
Generating and concatenating strings is expensive. Strings are immutable so any string operations creates a new temporary string that needs to be garbage-collected. Calculating dates this way for every item in a query result would create a lot of temporary strings that would waste RAM and CPU time.