I have two variables in type of DateTime, and I want to sum them, how can I do it开发者_StackOverflow中文版? 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 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);
}
}
You can use the DateTime.ToOADate Method :
DateTime D1 = DateTime.Today;
DateTime D2 = DateTime.Today.AddMonths(2);
double days = D1.ToOADate() + D2.ToOADate();
精彩评论