4

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

1

3 Answers 3

9

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;
Sign up to request clarification or add additional context in comments.

4 Comments

i have those lines: 00:00:01.2187500 CA_3 00:00:01.5468750 CWAC_1 they 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.
@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: Eh, you're right. I was nuts. You can use days and that should work out.
3

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

By the way, what are CA_3 and CWAC_1? Are they something standard or just the OP input format?
@Mehrdad: They're nothing I'm familiar with. I'm assuming they're unimportant :)
@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.)
0

You can use the DateTime.ToOADate Method :

DateTime D1 = DateTime.Today;
DateTime D2 = DateTime.Today.AddMonths(2);

double days = D1.ToOADate() + D2.ToOADate();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.