namespace YB.DeviceStand.Util.Extend { public static partial class Ext { /// /// 相差的月份 /// /// /// public static int ToMonth(this DateTime from) { DateTime to = DateTime.Now; if (to.Ticks < from.Ticks) { DateTime temp = from; from = to; to = temp; } double percFrom = (double)from.Day / DateTime.DaysInMonth(from.Year, from.Month); double percTo = (double)to.Day / DateTime.DaysInMonth(to.Year, to.Month); double months = (to.Year * 12 + to.Month) - (from.Year * 12 + from.Month); int month = (int)(months - percFrom + percTo); return month; } //// /// 相差的月份 /// /// 出生年月 /// 是否精确到周,false-否 /// public static decimal ToMonth(this DateTime? birthdate, bool IsWeek = false) { if (birthdate == null) { birthdate = DateTime.Now; } return ToMonth(birthdate.Value, IsWeek); } //// /// 相差的月份 /// /// 出生年月 /// 是否精确到周,false-否 /// public static decimal ToMonth(this DateTime birthdate, bool IsWeek = false) { DateTime now = DateTime.Now; int age = now.Year - birthdate.Year; if ( //当前月份小于出生月份,则不满足一年 now.Month < birthdate.Month //当前月份等于出生月份并且当前天小于出生天,则不满足一年 || (now.Month == birthdate.Month && now.Day < birthdate.Day)) { age--; } age = age < 0 ? 0 : age; decimal month = 0; if (IsWeek && age == 0) { month = (((now - birthdate).TotalDays / 7) / 4.0).ToDecimal(2); } else { month = now.Month - birthdate.Month; } return month <= 0 ? age * 12 : (month < 1 ? month : age * 12 + month); } } }