C # operator DateTime + =

I have two variables in a DateTime type and I want to summarize them, how can I do this? I get a compilation error that says DateTime dosen't has a + = operator

+3
source share
3 answers

Just to answer a comment in Mehrdad, answer - yes, it looks like both of them should be treated as TimeSpaninstead of values DateTime... and yes, you can also add time intervals together.

If you are using .NET 4, you can use a custom format string to parse the first part of the string, for example. "00: 00: 01,2187500".

Code example:

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
source

DateTime. . A DateTime , a TimeSpan . . TimeSpan DateTime values ​​– += :

dateTime += timeSpan;
+7

You can use the DateTime.ToOADate method :

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

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

Source: https://habr.com/ru/post/1750833/


All Articles