tags:

views:

89

answers:

2

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 +=

+5  A: 
Mehrdad Afshari
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?
@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
@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
@Adam: Eh, you're right. I was nuts. You can use `days` and that should work out.
Mehrdad Afshari
+2  A: 

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);
    }
}
Jon Skeet
@Jon: By the way, what are CA_3 and CWAC_1? Are they something standard or just the OP input format?
Mehrdad Afshari
@Mehrdad: They're nothing I'm familiar with. I'm assuming they're unimportant :)
Jon Skeet
he says the timeSpan does not have parseExat method....
nvm, it's working also with "TryParse method.. tanks!
@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