将十进制数添加到日期 - C#

Add decimal number to Date - C#

如何将小数(例如2.5)转换为年月(2年6个月)并将其添加到给定日期?我试过 DateTime.TryParse 但没用。

如果您使用它多年,则将您的浮点数乘以 12。2.5 变为 30 个月。然后使用 addmonths 函数。如果我输入 5 那么它将添加 60 个月,即 5 年

如果您的初始日期是 dt 而不是

dt = dt.AddMonths((int)(2.5*12));

通常您可以只添加 TimeSpan 或使用其中一种 Add 方法,如下所示:

decimal yearsToAdd = (decimal)2.5;

int years = (int)Math.Floor(yearsToAdd);
decimal months = yearsToAdd - years;
int actualMonths = (int) Math.Floor(months * 12); // or Ceiling or Round

DateTime x = DateTime.Now.AddYears(years).AddMonths(actualMonths);

问题是,当你的小数点不产生精确的月数时,你怎么知道多长时间,例如半个月是? 28.0 / 229.0 / 230.0 / 2 还是 31.0 / 2? 您会选择开始月份的长度还是可能结束的两个月之一?

decimal x =(decimal)2.5;

int nbYear = Convert.ToInt16(x);
var y = x - Math.Truncate(x);

int nbMonth =Convert.ToInt16 (y*12);
// MessageBox .Show (string.Format (" {0} years and {1} months ",nbYear ,nbMonth ));
DateTime dat=DateTime .Now ;  // or    given date
DateTime dat2 = dat.AddYears(nbYear).AddMonths(nbMonth);

如果月份是您的最小单位,那么正如许多人指出的那样,解决方案是将数字乘以 12。更准确的替代方法是使用刻度。

decimal years=3.14592M; // No idea where this came from.
long ticks = (long)(356.0M * (decimal)TimeSpan.TicksPerDay * years); 
DateTime futureDate=DateTime.Today.AddTicks(ticks);

请注意,解决方案不会补偿闰年。扩展它并不难 - 您需要计算期间的闰年数,并使用平均值而不是 356.0M 来计算每年的滴答声(即每年平均天数 * 每天滴答声)。