計算工齡(月份)的C#演算法
阿新 • • 發佈:2020-11-14
static int GetGongLing() { int GongLing = 0; string RuChangRiQi ="2020-01-30"; string HeSuanYueFen= "2020-6-1"; DateTime zhouQiStart = DateTime.Parse(HeSuanYueFen).AddDays(-1); DateTime RuChang; if (DateTime.TryParse(RuChangRiQi, out RuChang)) { Console.WriteLine(RuChang); int index = 0; var startRuChang = RuChang; while (true) { if (startRuChang.AddMonths(index) < zhouQiStart) { index++; } else break; } GongLing = index-1; } else { GongLing = 0; } return GongLing; }
注意不能寫成下面這種(不能一個月一個月累加判斷,要一次相加N次來判斷,起始index可以自己優化到一個接近範圍)
static int GetGongLing() { int GongLing = 0; string RuChangRiQi ="2020-01-30"; string HeSuanYueFen= "2020-7-1"; DateTime zhouQiStart = DateTime.Parse(HeSuanYueFen).AddDays(-1); DateTime zhouQiEnd = DateTime.Parse(HeSuanYueFen).AddMonths(1).AddD DateTime RuChang; if (DateTime.TryParse(RuChangRiQi, out RuChang)) { Console.WriteLine(RuChang); int index = 0; while (true) { RuChang=RuChang.AddMonths(index); if (RuChang < zhouQiStart) { index++; GongLing++; } else break; } } else { GongLing = 0; } return GongLing; }