繁体   English   中英

将十进制数添加到日期 - 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);

问题是,当你的小数不会产生exacat数月时,你怎么知道多长时间,例如半个月? 28.0 / 2 29.0 / 2 30.0 / 231.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来计算每年的蜱数(即平均每年的天数*每天的蜱数)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM