计算工龄(月份)的C#算法

目前自认为比较精确的算法

static int GetGongLing(string RuChangRiQi, string HeSuanYueFen)
{
    int GongLing = 0;
    DateTime zhouQiStart = DateTime.Parse(HeSuanYueFen);
    DateTime RuChang;
    if (DateTime.TryParse(RuChangRiQi, out RuChang))
    {
        Console.WriteLine(RuChang);
        int index = 0;
        var startRuChang = RuChang;
        while (true)
        {
            index++;
            if (startRuChang.AddMonths(index) < zhouQiStart)
            {
                continue;
            }
            else
            {
                index--;
                break;
            }
                
        }
        GongLing = index;
    }
    else
    {
        GongLing = 0;
    }
    return GongLing;
}

以下两种借位方式不合适,比如3.31到4.30算出的是0实际上应该是1个月

方式一:只计算月份

int year = dt1.Year - dt2.Year;
int month = dt1.Month - dt2.Month;
int day = dt1.Day - dt2.Day;
if (day < 0) month -= 1;
int totalMonth = year * 12 + month; 

方式二:计算全部

请自己nuget 元组和xmpCore

using Sharpen;
using System;
using System.Text;

namespace Test
{
public class CompareDate
{
/// <summary>
/// 获取两个时间间隔了多少年 月 天
/// </summary>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <returns></returns>
public static (int year, int month, int days) CalculateDate(DateTime startDate, DateTime endDate)
{
try
{
if (endDate < startDate)
return (0, 0, 0);

Calendar startCalendar = new GregorianCalendar(startDate.Year, startDate.Month - 1, startDate.Day);
Calendar now = GregorianCalendar.GetInstance(System.Globalization.CultureInfo.CurrentCulture);

now.SetTime(endDate);

int day = now.Get(CalendarEnum.DayOfMonth) - startCalendar.Get(CalendarEnum.DayOfMonth);
//月份从0开始计算,所以需要+1
int month = (now.Get(CalendarEnum.Month) + 1) - (startCalendar.Get(CalendarEnum.Month) + 1);
int year = now.Get(CalendarEnum.Year) - startCalendar.Get(CalendarEnum.Year);

//按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减。

if (day < 0)
{
month -= 1;
now.Set(CalendarEnum.Month, -1);//得到上一个月,用来得到上个月的天数。
day += now.GetMaximum(CalendarEnum.DayOfMonth);
}

if (month < 0)
{
month = (month + 12) % 12;
year--;
}

StringBuilder tag = new StringBuilder();

if (year > 0)
tag.Append(year + "岁");

if (month > 0)
tag.Append(month + "个月");

if (day > 0)
tag.Append(day + "天");

if (year == 0 && month == 0 && day == 0)
tag.Append("今日出生");

if (year < 0) year = 0;

System.Diagnostics.Debug.WriteLine(tag.ToString());

return (year, month, day);
}
catch (Exception er)
{
//DGHR.Util.Logger.Error(er);

return (0, 0, 0);
}
}

/// <summary>
/// 获取两个日期的总天数
/// </summary>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <returns></returns>
public static int? CalculateTotalDays(DateTime startDate, DateTime endDate)
{
if (endDate < startDate)
return null;

return (endDate - startDate).Days;
}
}
}

 

posted @ 2020-11-14 14:31  zhaogaojian  阅读(567)  评论(0编辑  收藏  举报