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 +=
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;
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With