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 +=
i have those lines: 00:00:01.2187500 CA_3 00:00:01.5468750 CWAC_1they are in a file. can i read the times as timeSpan and add them?
2010-06-19 18:56:46
@ahront: `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`.
Mehrdad Afshari
2010-06-19 18:57:53
@Merhrdad: Err, no. You cannot use years or months in the `TimeSpan` constructor, as they're not actual units of measure (they vary in length).
Adam Robinson
2010-06-19 19:01:09
@Adam: Eh, you're right. I was nuts. You can use `days` and that should work out.
Mehrdad Afshari
2010-06-19 19:04:47
+2
A:
Just to answer the comment in Mehrdad's answer - yes, it looks like those should both be regarded as TimeSpan
s 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);
}
}
Jon Skeet
2010-06-19 18:59:19
@Jon: By the way, what are CA_3 and CWAC_1? Are they something standard or just the OP input format?
Mehrdad Afshari
2010-06-19 19:07:01
@Mehrdad: They're nothing I'm familiar with. I'm assuming they're unimportant :)
Jon Skeet
2010-06-19 19:09:48
@aharont: Are you not using .NET 4? If not, I'm slightly surprised it *is* working as you can't specify your own format string (as far as I'm aware.)
Jon Skeet
2010-06-19 20:10:33