根据公历日期获取到农历日期信息(带星座)(C#)

直接上码,都有注释说明

 

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace ConsoleApp.Models
{
    public class ChineseCalendarModel
    {
        /// 
        /// 构造函数   CreateDate:2020-01-09 17:45:57;Author:Ling_bug
        /// 
        /// 
        public ChineseCalendarModel(DateTime date)
        {
            Init(date);
        }

        /// 
        /// 初始化   CreateDate:2020-01-09 17:46:28;Author:Ling_bug
        /// 
        /// 
        private void Init(DateTime date)
        {
            this.ParameterDate = date;

            char o = '、';
            //十天干
            string a = "甲、乙、丙、丁、戊、己、庚、辛、壬、癸";
            this.HeavenlyStems = a.Split(o);
            //十二地支
            string b = "子、丑、寅、卯、辰、巳、午、未、申、酉、戌、亥";
            this.EarthlyBranches = b.Split(o);
            //十二生肖
            string c = "鼠、牛、虎、兔、龙、蛇、马、羊、猴、鸡、狗、猪";
            this.ChineseZodiacs = c.Split(o);
            //月份
            string d = "正、二、三、四、五、六、七、八、九、十、十一、腊";
            this.Months = d.Split(o);
            //日期开头
            string e = "初、十、甘、三";
            this.DaysTitle = e.Split(o);
            //日期结尾
            string f = "一、二、三、四、五、六、七、八、九、十";
            this.Days = f.Split(o);

            InitConstellations();
            InitConstellationData();

            //获取农历日期
            InitChineseCalendarDate();
        }

        /// 
        /// 找到参数对应的星座   CreateDate:2020-01-10 11:03:49;Author:Ling_bug
        /// 
        private void InitConstellationData()
        {
            int month = this.ParameterDate.Month;
            int day = this.ParameterDate.Day;
            //找到与开始日期匹配的或者结束日期匹配的(说明该参数日期是这个星座的开始的那一天或者结束的那一天)
            var equalModel = this.Constellations.FirstOrDefault(r => (r.BeginMonth == month && r.BeginDay == day) || (r.EndMonth == month && r.EndDay == day));
            if (equalModel == null)
            {
                bool isFindFromEnd = true;

                //找到开始月相同的
                var beginMonthModel = this.Constellations.FirstOrDefault(r => r.BeginMonth == month);
                //如果找到了并且当前日大于开始日,则匹配正确
                if (beginMonthModel != null && day > beginMonthModel.BeginDay)
                {
                    this.ConstellationName = beginMonthModel.ConstellationName;
                    isFindFromEnd = false;
                }

                //如果没有找到,则匹配结束的
                if (isFindFromEnd)
                {
                    //找到结束月相同的
                    var endMonthModel = this.Constellations.FirstOrDefault(r => r.EndMonth == month);
                    //如果有结束月相同的,并且当前日小于结束日的,则匹配成功
                    if (endMonthModel != null && day < endMonthModel.EndDay)
                    {
                        this.ConstellationName = endMonthModel.ConstellationName;
                    }
                }
            }
            else
            {
                this.ConstellationName = equalModel.ConstellationName;
            }
        }

        /// 
        /// 初始化星座集合   CreateDate:2020-01-10 11:03:23;Author:Ling_bug
        /// 
        private void InitConstellations()
        {
            this.Constellations = new List()
            {
                new ConstellationModel("白羊", "3-21", "4-19"),
                new ConstellationModel("金牛", "4-20", "5-20"),
                new ConstellationModel("双子", "5-21", "6-21"),
                new ConstellationModel("巨蟹", "6-22", "7-22"),
                new ConstellationModel("狮子", "7-23", "8-22"),
                new ConstellationModel("处女", "8-23", "9-22"),
                new ConstellationModel("天秤", "9-23", "10-23"),
                new ConstellationModel("天蝎", "10-24", "11-22"),
                new ConstellationModel("射手", "11-23", "12-21"),
                new ConstellationModel("摩羯", "12-22", "1-19"),
                new ConstellationModel("水瓶", "1-20", "2-18"),
                new ConstellationModel("双鱼", "2-19", "3-20")
            };
        }

        /// 
        /// 获取到农历日期   CreateDate:2020-01-09 17:46:52;Author:Ling_bug
        /// 
        private void InitChineseCalendarDate()
        {
            //农历日期服务类
            var calendarService = new ChineseLunisolarCalendar();

            //农历年
            this.Year = calendarService.GetYear(this.ParameterDate);
            //农历月(闰年时不同)
            this.Month = calendarService.GetMonth(this.ParameterDate);
            //农历日
            this.Day = calendarService.GetDayOfMonth(this.ParameterDate);

            //获取到该年的闰月
            this.LeapMonth = calendarService.GetLeapMonth(this.Year);
            this.InitResultMonth();
            this.InitLunisolarTitle();

            //农历日期字符串
            this.ChineseCalendarDateStr = $"{this.HeavenlyStem}{this.EarthlyBranch}{this.ChineseZodiac}年{this.IsLeapTitle}{this.MonthTitle}月{this.DayTitle}[{this.Year}-{this.ResultMonth}-{this.Day}]";
        }

        /// 
        /// 获取到真正的农历月(考虑闰月的情况)   CreateDate:2020-01-09 17:48:31;Author:Ling_bug
        /// 
        private void InitResultMonth()
        {
            this.ResultMonth = this.Month;
            if (this.LeapMonth > 0)
            {
                this.IsLeap = this.Month == this.LeapMonth;
                //如果当前月大于等于闰月,则需要减一(例如闰月是7月,查询出来是8月,实际上当前月份其实是7月,所以需要减一)
                if (this.Month >= this.LeapMonth)
                {
                    this.ResultMonth--;
                }
            }
            this.IsLeapTitle = this.IsLeap ? "闰" : string.Empty;
        }

        /// 
        /// 获取到要显示的title   CreateDate:2020-01-09 18:23:35;Author:Ling_bug
        /// 
        private void InitLunisolarTitle()
        {
            var yearHelper = this.Year - 4;
            var indexHeavenlyStem = yearHelper % 10;
            var indexEarthlyBranchAndChineseZodiac = yearHelper % 12;

            this.HeavenlyStem = this.HeavenlyStems[indexHeavenlyStem];
            this.EarthlyBranch = this.EarthlyBranches[indexEarthlyBranchAndChineseZodiac];
            this.ChineseZodiac = this.ChineseZodiacs[indexEarthlyBranchAndChineseZodiac];

            this.MonthTitle = this.Months[this.ResultMonth - 1];

            InitDayTitle();
        }

        /// 
        /// 获取到年月日中日的title   CreateDate:2020-01-09 18:24:13;Author:Ling_bug
        /// 
        private void InitDayTitle()
        {
            var dayHelper = this.Day - 1;
            var indexHelperDayDiv = dayHelper / 10;
            if (this.Day == 20 || this.Day == 30)
            {
                this.DayTitle = this.Days[indexHelperDayDiv] + this.DaysTitle[1];
            }
            else
            {
                var indexHelperDayMod = dayHelper % 10;
                this.DayTitle = this.DaysTitle[indexHelperDayDiv] + this.Days[indexHelperDayMod];
            }
        }

        /// 
        /// 需要转换的公历日期参数
        /// 
        public DateTime ParameterDate { get; set; }

        /// 
        /// 农历年
        /// 
        public int Year { get; set; }

        /// 
        /// 农历月(闰月时不同)
        /// 
        public int Month { get; set; }

        /// 
        /// 农历月(自动计算考虑闰月的情况)
        /// 
        public int ResultMonth { get; set; }

        /// 
        /// 农历日
        /// 
        public int Day { get; set; }

        /// 
        /// 今年哪个月是闰月
        /// 
        public int LeapMonth { get; set; }

        /// 
        /// 当前是否是闰月
        /// 
        public bool IsLeap { get; set; }

        /// 
        /// 十天干
        /// 
        public string[] HeavenlyStems { get; private set; }

        /// 
        /// 十二地支
        /// 
        public string[] EarthlyBranches { get; private set; }

        /// 
        /// 十二生肖
        /// 
        public string[] ChineseZodiacs { get; private set; }

        /// 
        /// 星座
        /// 
        public List Constellations { get; private set; }

        /// 
        /// 月
        /// 
        public string[] Months { get; private set; }

        /// 
        /// 日期头
        /// 
        public string[] DaysTitle { get; private set; }

        /// 
        /// 日期尾
        /// 
        public string[] Days { get; private set; }

        /// 
        /// 天干
        /// 
        public string HeavenlyStem { get; set; }

        /// 
        /// 地支
        /// 
        public string EarthlyBranch { get; set; }

        /// 
        /// 生肖
        /// 
        public string ChineseZodiac { get; set; }

        /// 
        /// 星座
        /// 
        public string ConstellationName { get; set; }

        /// 
        /// 月
        /// 
        public string MonthTitle { get; set; }

        /// 
        /// 日期
        /// 
        public string DayTitle { get; set; }

        /// 
        /// 闰月
        /// 
        public string IsLeapTitle { get; set; }

        /// 
        /// 结果字符串
        /// 
        public string ChineseCalendarDateStr { get; set; }
    }
}

匹配星座还有一种写法:

            var constellationList = this.Constellations.FindAll(r =>
            {
                bool begin = r.BeginMonth == month && r.BeginDay == day;
                bool end = r.EndMonth == month && r.EndDay == day;
                bool granterBegin = r.BeginMonth == month && day > r.BeginDay;
                bool lessEnd = r.EndMonth == month && day < r.EndDay;
                return begin || end || granterBegin || lessEnd;
            });
            if (constellationList.Any())
            {
                if (constellationList.Count == 1)
                {
                    this.ConstellationName = constellationList.First().ConstellationName;
                }
                else
                {
                    throw new Exception($"匹配到{constellationList.Count}个星座,month = {month},day = {day}");
                }
            }
            else
            {
                throw new Exception($"未匹配到星座,month = {month},day = {day}");
            }

 

星座对象:

using System;

namespace ConsoleApp.Models
{
    /// 
    /// 星座   CreateDate:2020-01-10 10:19:23;Author:Ling_bug
    /// 
    public class ConstellationModel
    {
        public ConstellationModel(string constellationName, string beginDate, string endDate)
        {
            this.ConstellationName = constellationName;
            if (this.ConstellationName.Length == 2)
            {
                this.ConstellationName += "座";
            }
            this.BeginDate = Convert.ToDateTime(beginDate);
            this.EndDate = Convert.ToDateTime(endDate);
            this.BeginMonth = this.BeginDate.Month;
            this.BeginDay = this.BeginDate.Day;
            this.EndMonth = this.EndDate.Month;
            this.EndDay = this.EndDate.Day;
        }

        public DateTime BeginDate { get; private set; }

        public int BeginMonth { get; private set; }

        public int BeginDay { get; private set; }

        public int EndMonth { get; private set; }

        public int EndDay { get; private set; }

        public DateTime EndDate { get; private set; }

        public string ConstellationName { get; private set; }
    }
}

 

测试一下:

测试代码:

using System;
using System.Collections.Generic;
using System.Linq;
using ConsoleApp.Models;

namespace ConsoleApp.Services
{
    public class TestChineseCalendarService
    {
        public static void Run1()
        {
            var model = new ChineseCalendarModel(DateTime.Now);
            int index = 0;
            foreach (var proc in model.GetType().GetProperties())
            {
                var value = proc.GetValue(model);
                Console.WriteLine($"{++index}.{proc.Name}:{value}");
            }
        }

        public static void Run2()
        {
            var begin = Convert.ToDateTime("2020-1-1");
            var end = Convert.ToDateTime("2020-12-31");
            int count = 0;
            var list = new List();
            while (begin <= end)
            {
                var item = new ChineseCalendarModel(begin);
                list.Add(item);
                Console.WriteLine(begin.ToString("yyyy-MM-dd") + ":" + item.ChineseCalendarDateStr + $"[{item.ConstellationName}]");
                begin = begin.AddDays(1);
                count++;
            }

            Console.WriteLine();
            Console.WriteLine($"共{count}条");
            Console.WriteLine($"未匹配到星座的:{list.Count(r => string.IsNullOrWhiteSpace(r.ConstellationName))}");
        }
    }
}

 

Run1测试结果:

根据公历日期获取到农历日期信息(带星座)(C#)_第1张图片

Run2测试结果:

根据公历日期获取到农历日期信息(带星座)(C#)_第2张图片

 

 

Ending~

你可能感兴趣的:(C#/.NET)