c# - 在 nodatime 上添加两个句点

标签 c# asp.net nodatime

其中listObjAge是一个有多个句点的列表;

Period objTotalPeriod = listObjAge[0].period;
for (int i = 1; i < listObjAge.Count; i++) {
   objTotalPeriod += listObjAge[i].period;
}

简而言之:
我得到了什么:

listObjAge[0].period + listObjAge[1].period = ????.
2 yr 1 mnth 28 days  + 0 yr 8 mnth 30 days  = 2 yr 9 mnth 58 days 
// this result is not wrong but is there any way to correctly add days for the above code.

我期待的是:

2 yr 1 mnth 28 days  + 0 yr 8 mnth 30 days  = 2 yr 10 mnth 28 days 

如您所见,我想添加两个时期的结果。有什么方法可以使用 nodatime 实现吗?

已解决:
我知道它在理论上是不正确的。但它对我有用。

int intDays = 0;
for (int i = 0; i < listObjAge.Count; i++) {
     intDays += listObjAge[i].period.Days; // adding all the days for every period
}

strYear = (intDays / 365).ToString();
strMonth = ((intDays % 365) / 30).ToString();
strDays = ((intDays % 365) % 30).ToString();

最佳答案

您应该查看描述算术的 Noda Time 用户指南 http://nodatime.org/2.0.x/userguide/arithmetic - 查看“添加句点”部分了解更多信息。


最容易想到这可能与示例混淆的地方。假设我们将“一个月减三天”添加到 2011 年 1 月 30 日:

Period period = Period.FromMonths(1) - Period.FromDays(3);
LocalDate date = new LocalDate(2011, 1, 30);
date = date + period;

如果您将这个谜题交给真人,他们很可能会等到最后一刻检查有效性,然后得出“2 月 27 日”的答案。 Noda Time将在2月25日给出答案,因为上面的代码被有效评估为:

Period period = Period.FromMonths(1) - Period.FromDays(3);
LocalDate date = new LocalDate(2011, 1, 30);
date = date + Period.FromMonths(1); // February 28th (truncated)
date = date - Period.FromDays(3); // February 25th

The benefit of this approach is simplicity and predictability: when you know the rules, it's very easy to work out what Noda Time will do. The downside is that if you don't know the rules, it looks like it's broken.


用你的代码

根据文档,您得到的结果是基于“规则”的预期行为。简单地说,您对两个两个周期的加法运算将评估为:

Years (2 + 0) = 2
Months(1 + 8) = 9
Days (28 + 30) = 58

Your comment:
this result is not wrong but is there any way to correctly add days for the above code.

“正确”是什么意思?你是说 28 + 30 = 58 不正确?


备选方案

int days = 28 + 30; // carry over your days and +1 month or whatever logic you had in mind
int months = 1 + 8;
Period p1 = new PeriodBuilder { Days = days, Months = months }.Build();

关于c# - 在 nodatime 上添加两个句点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44276026/

相关文章:

javascript - 通过Request.Form传递二维数组(或对象数组)?

javascript - 使用带条件的循环创建 Javascript 对象

c# - 基于 header 值的 ASP.Net Core Blazor : How to load different _Host. cshtml 文件

.net - 我应该如何将本地 DateTime 转换为 Instant?

c# - Noda 时间单元测试 XML 错误

c# - Visio 形状 - 获取 X、Y 位置

c# - 类名周围的括号在 C# 类中意味着什么

c# - 计算器总失败

c# - 正确部署了Azure中的所有文件,但仍然无法看到网页

c# - Noda Time - 从 DateTime 和 TimeZoneId 创建 ZonedDateTime