gpt4 book ai didi

C# 日期操作

转载 作者:太空宇宙 更新时间:2023-11-03 17:08:34 27 4
gpt4 key购买 nike

我做错了吗?

                DateTime previousDay = new DateTime(year, month, day);
string test1 = previousDay.ToString();
previousDay.Subtract(new TimeSpan(1, 0, 0, 0));
string test2 = previousDay.ToString();
previousDay.AddDays(-1);
string test3 = previousDay.ToString();

由于某些对大多数人来说可能显而易见的原因,日期不会从 test1 更改为 test3。
请帮忙!

最佳答案

DateTime 是不可变的 - 当您调用 Subtract 时,它不会更改调用的目标,它返回一个新值:

DateTime previousDay = new DateTime(year, month, day);
string test1 = previousDay.ToString();
previousDay = previousDay.Subtract(new TimeSpan(1, 0, 0, 0));
string test2 = previousDay.ToString();
previousDay = previousDay.Subtract(new TimeSpan(1, 0, 0, 0));
string test3 = previousDay.ToString();

尽管我会使用 - 运算符和 TimeSpan.FromDays:

DateTime previousDay = new DateTime(year, month, day);
string test1 = previousDay.ToString();
previousDay = previousDay - TimeSpan.FromDays(1);
string test2 = previousDay.ToString();
previousDay = previousDay - TimeSpan.FromDays(1);
string test3 = previousDay.ToString();

或者更好的是,使用 AddDays:

DateTime previousDay = new DateTime(year, month, day);
string test1 = previousDay.ToString();
previousDay = previousDay.AddDays(-1);
string test2 = previousDay.ToString();
previousDay = previousDay.AddDays(-1);
string test3 = previousDay.ToString();

或者更好的是,使用 Noda Time :)

LocalDate date = new LocalDate(year, month, day);
string test1 = previousDay.ToString();
date = date.PlusDays(-1);
string test2 = previousDay.ToString();
date = date.PlusDays(-1);
string test3 = previousDay.ToString();

或者:

LocalDate date = new LocalDate(year, month, day);
string test1 = previousDay.ToString();
date = date + Period.FromDays(-1);
string test2 = previousDay.ToString();
date = date + Period.FromDays(-1);
string test3 = previousDay.ToString();

关于C# 日期操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9175317/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com