3つ以上のDatetime型の変数を比較する方法

UiPathというよりはVBの質問になってしまって恐縮ですが…
複数のDatetime型の変数の中から最も近い(遠い)ものを選ぶという処理をやりたい場合に、
Datetime.Compare(A,B)を繰り返すような力技ではなく簡潔に記述できる方法は無いでしょうか?

HI @wewew

This a sample Vb code

System.DateTime theDay = new System.DateTime(System.DateTime.Today.Year, 7, 28);
int compareValue;

try
{
compareValue = theDay.CompareTo(DateTime.Today);
}
catch (ArgumentException)
{
Console.WriteLine(“Value is not a DateTime”);
return;
}

if (compareValue < 0)
System.Console.WriteLine(“{0:d} is in the past.”, theDay);
else if (compareValue == 0)
System.Console.WriteLine(“{0:d} is today!”, theDay);
else // compareValue > 0
System.Console.WriteLine(“{0:d} has not come yet.”, theDay);

Try to use this code
Regards
Gokul

こんにちは

まず質問内容の確認になりますが、
ある一つの日付が決まっていて、それに対する複数の日付のうち間隔が最小のものを選択する
でしょうか、あるいは
任意の複数の日付のうち、最小の間隔のものを抽出するのでしょうか?

いずれにしても方法はいくつかあると思いますが、
前者なら、比較対象のDateTimeをtargetDate、複数の日付が格納された配列をdtArrayとすると、例えば

dtArray.Where(Function(d) Math.Abs((d-targetDate).TotalSeconds)=dtArray.Min(Function(d2) Math.Abs((d2-targetDate).TotalSeconds))).First()

のような感じで算出できると思います。

後者の場合は、例えば、上記の事前にdtArrayをソートしておいて、その前後の間隔が最初となる組を結果とする方法が考えられます

1 Like