[英]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 / 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來計算每年的蜱數(即平均每年的天數*每天的蜱數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.