MeiRiYiCheng_1_old/Plugin/YB.DeviceStand/YB.DeviceStand.Util/Extend/Ext.DateTime.cs

71 lines
2.5 KiB
C#

namespace YB.DeviceStand.Util.Extend
{
public static partial class Ext
{
/// <summary>
/// 相差的月份
/// </summary>
/// <param name="birthdate"></param>
/// <returns></returns>
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;
}
//// <summary>
/// 相差的月份
/// </summary>
/// <param name="birthdate">出生年月</param>
/// <param name="IsWeek">是否精确到周,false-否</param>
/// <returns></returns>
public static decimal ToMonth(this DateTime? birthdate, bool IsWeek = false)
{
if (birthdate == null)
{
birthdate = DateTime.Now;
}
return ToMonth(birthdate.Value, IsWeek);
}
//// <summary>
/// 相差的月份
/// </summary>
/// <param name="birthdate">出生年月</param>
/// <param name="IsWeek">是否精确到周,false-否</param>
/// <returns></returns>
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);
}
}
}