日時/時間の減算

日時(DateTime構造体)は日付同士の加算はできないが、減算はできる。
時間(TimeSpan構造体)は加減算が可能。

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.IO;
  6 
  7 namespace Program
  8 {
  9     class Program {
 10         static void Main(string[] arg) {
 11             var past = new DateTime(2018, 3, 20);
 12             var now = DateTime.Now;
 13 
 14             var sub = now - past;
 15             var sub2 = now.Subtract(past);
 16 
 17             // var add = now + past;
 18             // Operator `+' cannot be applied to operands of type `System.DateTime' and `System.DateTime'
 19 
 20             Console.WriteLine("sub; {0}", sub);
 21             Console.WriteLine("sub2: {0}", sub2);
 22 
 23             // 10days, 5hours, 6minutes and 1seconds
 24             var tSpan = new TimeSpan(10, 5, 6, 1);
 25 
 26             var tSub = now - tSpan;
 27             var tSub2 = now.Subtract(tSpan);
 28 
 29             var tAdd = now + tSpan;
 30             var tAdd2 = now.Add(tSpan);
 31 
 32             Console.WriteLine("tSub: {0}", tSub);
 33             Console.WriteLine("tSub2: {0}", tSub2);
 34 
 35             Console.WriteLine("tAdd: {0}", tAdd);
 36             Console.WriteLine("tAdd2: {0}", tAdd2);
 37         }
 38     }
 39 }
sub; 1.16:09:16.2632200
sub2: 1.16:09:16.2632200
tSub: 2018/03/11 11:03:15
tSub2: 2018/03/11 11:03:15
tAdd: 2018/03/31 21:15:17
tAdd2: 2018/03/31 21:15:17