C# 阳历与农历互转

  System.Globalization命名空间下提供了专门用于计算中国农历的ChineseLunisolarCalendar类,从EastAsianLunisolarCalendar派生而来。

阳历转农历

        ChineseLunisolarCalendar cncld = new ChineseLunisolarCalendar();
        DateTime dt = new DateTime(2023, 6, 17);
        int year = cncld.GetYear(dt);
        // 是否有闰月,返回正整数(比如2023年闰2月,返回值为3)
        int flag = cncld.GetLeapMonth(year);
        //有闰月则实际月份减1
        int month = flag > 0 ? cncld.GetMonth(dt) - 1 : cncld.GetMonth(dt);
        int day = cncld.GetDayOfMonth(dt);
        Console.WriteLine($"{dt:d},农历:{year}年{month}月{day}日");

农历转阳历

        month = flag > 0 ? month + 1 : month; //有闰月则月份加1后转换
        DateTime dtnl = cncld.ToDateTime(year, month, day, 0, 0, 0, 0);
        Console.WriteLine($"{dtnl}");
posted @ 2021-09-07 16:33  一纸年华  阅读(1307)  评论(2编辑  收藏  举报