c#实现阳历转干支历

我们需要知道以下规则:

  • 年干支:以公历4年为甲子年开始,每六十年一个循环。
  • 月干支:每年从正月(农历)的干支开始,按地支顺序推移,天干则根据年干来推算。
  • 日干支:以公历1月1日为甲子日开始,每六十天一个循环。
  • 时干支:每天从子时(23:00-01:00)开始,按地支顺序推移,天干则根据日干来推算。
using System;

public class ChineseEraConverter
{
    private static string[] TianGan = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
    private static string[] DiZhi = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };

    public static string GetYearGanZhi(int year)
    {
        int index = year - 4;
        return TianGan[index % 10] + DiZhi[index % 12];
    }

    public static string GetMonthGanZhi(int year, int month)
    {
        string yearGan = GetYearGanZhi(year)[0].ToString();
        int monthIndex = (year - 4) % 12;
        int tianGanIndex = Array.IndexOf(TianGan, yearGan) * 2 + monthIndex % 2;
        return TianGan[tianGanIndex % 10] + DiZhi[monthIndex];
    }

    public static string GetDayGanZhi(DateTime date)
    {
        DateTime baseDate = new DateTime(1900, 1, 31); // 1900年1月31日为甲子日
        TimeSpan ts = date - baseDate;
        int days = ts.Days + 10; // 加10是因为1900年1月31日是甲子日,不是甲子年的开始
        return TianGan[days % 10] + DiZhi[days % 12];
    }

    public static string GetHourGanZhi(string dayGan, int hour)
    {
        int tianGanIndex = Array.IndexOf(TianGan, dayGan[0].ToString());
        int diZhiIndex = (hour + 1) / 2; // 从23:00开始算子时
        return TianGan[(tianGanIndex * 2 + diZhiIndex) % 10] + DiZhi[diZhiIndex % 12];
    }
}

class Program
{
    static void Main()
    {
        Console.Write("请输入公历年份:");
        int year = int.Parse(Console.ReadLine());
        Console.Write("请输入公历月份:");
        int month = int.Parse(Console.ReadLine());
        Console.Write("请输入公历日期:");
        int day = int.Parse(Console.ReadLine());
        Console.Write("请输入小时(0-23):");
        int hour = int.Parse(Console.ReadLine());

        DateTime date = new DateTime(year, month, day);

        string yearGanZhi = ChineseEraConverter.GetYearGanZhi(year);
        string monthGanZhi = ChineseEraConverter.GetMonthGanZhi(year, month);
        string dayGanZhi = ChineseEraConverter.GetDayGanZhi(date);
        string hourGanZhi = ChineseEraConverter.GetHourGanZhi(dayGanZhi, hour);

        Console.WriteLine($"{year}{month}{day}{hour}时的干支是:");
        Console.WriteLine($"年干支:{yearGanZhi}");
        Console.WriteLine($"月干支:{monthGanZhi}");
        Console.WriteLine($"日干支:{dayGanZhi}");
        Console.WriteLine($"时干支:{hourGanZhi}");
    }
}

这段代码定义了四个方法来分别计算年、月、日、时的干支,然后在Main方法中读取用户输入的年、月、日、时,调用这些方法,并输出结果。

注意,日干支的计算是基于1900年1月31日为甲子日的,这是历史规定的一个起点。时干支的计算中,小时是从0到23,其中23:00-01:00对应子时。在计算时干支时,需要对天干进行修正,因此这里使用了(hour + 1) / 2

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值