DateTime は不変のオブジェクト型であるため、オブジェクトの時刻を変更 (またはシフト) する必要がある場合は、新しい DateTime オブジェクトを作成する必要があります。
DateTime.AddHours が機能しないように見えるのはなぜですか?
変数が宣言され、値が同じレキシカルスコープで設定されている場合は問題ありません。異なるレキシカルスコープで値を宣言して設定していることを除いて。通常、「DateTime from_instant = null;」を実行します。少なくとも値があるので、設定後に使用できます。ただし、DateTime では、一度設定した値は変更できません。では、「from_instant.AddHours(-10);」を実行してオブジェクトの値を調整するにはどうすればよいですか? たとえば、それが宣言されたレキシカルスコープの外ですか?
以下の私の場合、「from_instant」をリセットするたびに変更されません。変更できるようにしたいです。不変であるため、通常はどのように値をリセットしますか?
DateTime from_instant = DateTime.Now;
bool set_scan_start_instant_to_last_scan_instant = Convert.ToBoolean(GetConfig("set_scan_start_instant_to_last_scan_instant"));
if (set_scan_start_instant_to_last_scan_instant)
{
from_instant = GetScanTimeFromFile(@".\last_scan_instant.txt");
from_instant = DateTime.Now;
}
else
{
if (!string.IsNullOrEmpty(scan_interval_minutes))
{
from_instant = DateTime.Now.AddMinutes(Convert.ToInt32(scan_interval_minutes));
}
else if (!string.IsNullOrEmpty(scan_interval_hours))
{
from_instant = DateTime.Now.AddHours(Convert.ToInt32(scan_interval_hours));
}
else if (!string.IsNullOrEmpty(scan_interval_days))
{
from_instant = DateTime.Now.AddDays(Convert.ToInt32(scan_interval_days));
}
}
DateTime to_instant = DateTime.Now;
WriteScanTimeToFile(@".\last_scan_instant.txt", to_instant.ToString());
Console.WriteLine("from_instant: " + from_instant.ToString());
Console.WriteLine("to_instant: " + to_instant.ToString());