• C# 阳历转阴历


    前言

    需求:需要根据当前日期,获取阴历日期。原文传送门

    具体实现

    代码如下图所示:

    声明农历日月,代码如下所示:

    /// <summary>
    /// 农历日月
    /// </summary>
    private static string[] months = {
      "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"
    };
    private static string[] days1 = { "初", "十", "廿", "三" };
    private static string[] days = {
       "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"
    };
    

    返回农历月,代码如下所示:

    /// <summary>
    /// 返回农历月
    /// </summary>
    /// <param name="month">月份</param>
    /// <returns></returns>
    public static string GetLunisolarMonth(int month)
    {
        if (month < 13 && month > 0)
        {
           return months[month - 1];
        }
        throw new ArgumentOutOfRangeException("无效的月份!");
    }
    

    返回农历日,代码如下所示:

    /// <summary>
    /// 返回农历日
    /// </summary>
    /// <param name="day"></param>
    /// <returns></returns>
    public static string GetLunisolarDay(int day)
    {
        if (day > 0 && day < 32)
        {
            if (day != 20 && day != 30)
            {
                return string.Concat(days1[(day - 1) / 10], days[(day - 1) % 10]);
            }
            else
            {
                return string.Concat(days[(day - 1) / 10], days1[1]);
             }
          }
         throw new ArgumentOutOfRangeException("无效的日!");
    }
    

    最后,传入日期。代码如下所示:

    /// <summary>
    /// 阳历转阴历
    /// </summary>
    /// <returns></returns>
    public string GetYdataBydata(DateTime m_yData)
    {
        string lunarDate = string.Empty;
        ChineseLunisolarCalendar cCalendar = new ChineseLunisolarCalendar();
        int lyear = cCalendar.GetYear(m_yData);
        int lmonth = cCalendar.GetMonth(m_yData);
        int lday = cCalendar.GetDayOfMonth(m_yData);
        //获取闰月, 0 则表示没有闰月
        int leapMonth = cCalendar.GetLeapMonth(lyear);
        bool isleap = false;
        if (leapMonth > 0)
        {
            if (leapMonth == lmonth)
            {
               //闰月
               isleap = true;
               lmonth--;
             }
             else if (lmonth > leapMonth)
             {
                lmonth--;
             }
       }
       lunarDate= string.Concat(isleap ? "闰" : string.Empty, GetLunisolarMonth(lmonth), "月", GetLunisolarDay(lday));
        return lunarDate;
    }
    
  • 相关阅读:
    mysql环境搭建
    php基础:查看上次插入的主键和影响的行数及关闭mysql连接
    php基础:文件包含与引用 require和include的区别
    php基础:echo和print_r和var_dump的区别
    php基础:变量检测
    php基础:动态变量名
    php基础:代码的短路特性和运算符优先级
    php基础:三元运算符及比较3个数的大小
    php基础:字符串基本函数
    php基础:数组的定义和遍历
  • 原文地址:https://www.cnblogs.com/ZengJiaLin/p/14464817.html
Copyright © 2020-2023  润新知