I have two variables in type of DateTime, and I want to sum them, how can I do it? I get compilation error that says DateTime dosen't have operator +=
3 Answers
You cannot add two DateTime values together. It wouldn't have any meaning. A DateTime represents a single point in time, whereas a TimeSpan represents a duration. Adding a point in time to a duration results in another point in time. You can only add TimeSpan values to DateTime values–and it does support += in that case:
dateTime += timeSpan;
4 Comments
TimeSpan has a bunch of constructors that take years, months, days, hours, ... just like DateTime. So yes, you should read the duration value as TimeSpan and add it to your DateTime.TimeSpan constructor, as they're not actual units of measure (they vary in length).days and that should work out.Just to answer the comment in Mehrdad's answer - yes, it looks like those should both be regarded as TimeSpans instead of DateTime values... and yes, you can add time spans together too.
If you're using .NET 4, you can use a custom format string to parse the first part of the lines, e.g. "00:00:01.2187500".
Sample code:
using System;
using System.Globalization;
public class Test
{
static void Main()
{
string line1 = "00:00:01.2187500 CA_3";
string line2 = "00:00:01.5468750 CWAC_1";
TimeSpan sum = ParseLine(line1) + ParseLine(line2);
Console.WriteLine(sum);
}
static TimeSpan ParseLine(string line)
{
int spaceIndex = line.IndexOf(' ');
if (spaceIndex != -1)
{
line = line.Substring(0, spaceIndex);
}
return TimeSpan.ParseExact(line, "hh':'mm':'ss'.'fffffff",
CultureInfo.InvariantCulture);
}
}
3 Comments
You can use the DateTime.ToOADate Method :
DateTime D1 = DateTime.Today;
DateTime D2 = DateTime.Today.AddMonths(2);
double days = D1.ToOADate() + D2.ToOADate();