본문 바로가기
C#

[C#] 음력 변환

by Jcoder 2023. 10. 27.

KoreanLunisolarCalendar

 

KoreanLunisolarCalendar 클래스 (System.Globalization)

시간을 월, 일 및 연도로 구분해서 표시합니다. 연도는 그레고리오력을 사용하여 계산되고 일 및 월은 음양력을 사용하여 계산됩니다.

learn.microsoft.com

 

// See https://aka.ms/new-console-template for more information

using System.Globalization;

Console.WriteLine("Hello, World!");

// KoreanLunisolarCalendar 클래스의 인스턴스를 생성합니다.
var koreanLunisolarCalendar = new KoreanLunisolarCalendar();

var lunarDate2 = $"{koreanLunisolarCalendar.GetYear(nowDate2)}년 {koreanLunisolarCalendar.GetMonth(nowDate2)}월 {koreanLunisolarCalendar.GetDayOfMonth(nowDate2)}일";
Console.WriteLine(lunarDate2);

Console.Read();

작성일 기준 2023-10-27, 음력은 2023-09-13 이다.

그러나 위 코드로 단순하게 변환하면 2023-10-13이 나온다.

 

윤달 계산도 필요하다.

// See https://aka.ms/new-console-template for more information

using System.Globalization;

Console.WriteLine("Hello, World!");

// KoreanLunisolarCalendar 클래스의 인스턴스를 생성합니다.
var koreanLunisolarCalendar = new KoreanLunisolarCalendar();

// 현재 날짜를 설정합니다.
var nowDate = DateTime.Now;

// KoreanLunisolarCalendar 클래스의 GetYear, GetMonth, GetDayOfMonth 메서드를 사용하여,
// 현재 날짜의 연도, 월, 일을 구합니다.
var year = koreanLunisolarCalendar.GetYear(nowDate);
var month = koreanLunisolarCalendar.GetMonth(nowDate);
var day = koreanLunisolarCalendar.GetDayOfMonth(nowDate);

// 만약 해당 연도에 윤달이 있다면,
if (koreanLunisolarCalendar.GetMonthsInYear(year) > 12)
{
    // 윤달의 위치를 구합니다.
    int leapMonth = koreanLunisolarCalendar.GetLeapMonth(year);

    // 만약 현재 월이 윤달 이후의 월이라면, 현재 월을 1달씩 감소시킵니다.  
    if (month > leapMonth)  
    {  
        month--;  
    }  
    // 만약 현재 월이 윤달인데, 현재 일이 해당 월의 마지막 날보다 크다면,  
    // 현재 일을 1일씩 감소시킵니다.  
    else if (month == leapMonth && day > koreanLunisolarCalendar.GetDaysInMonth(year, month))  
    {  
        day--;  
    }  
}

var lunarDate = $"{year}년 {month}월 {day}일";
Console.WriteLine(lunarDate);

Console.Read();