Do not use addition and subtraction to calculate the year for Japanese calendar. JapaneseCalendar class has functions for this purpose. (GetEra,GetYear)
using System;
using System.Collections.Generic;
using System.Globalization;
internal class Program
{
static void Main()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-us");
//System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("ja-jp");
DateTime d1 = new DateTime(2024, 02, 29, 6, 20, 40, DateTimeKind.Unspecified);
Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
JapaneseCalendar myCal = new JapaneseCalendar();
var eraType = myCal.GetEra(d1);
var eraYear = myCal.GetYear(d1);
bool isLeapYear = myCal.IsLeapYear(eraYear, eraType);
DateTime d2 = new DateTime(eraYear, 1, 1, 0, 0, 0, DateTimeKind.Unspecified); // For format 'y' :: If Thread is Japanese culture , 'y' will be '0006年'
Console.WriteLine("New DateTime (subtracting years) = {0:dd} {1:y}, {0:hh}:{0:mm}:{0:ss}", d1, d2);
Console.WriteLine(isLeapYear);
JapaneseCalendar jpCal = new JapaneseCalendar();
CultureInfo jpCaulture = new CultureInfo("ja-jp", false);
jpCaulture.DateTimeFormat.Calendar = jpCal;
// JapaneseCalendar has a range of dates that can be processed, and outside of that range cannot be processed correctly.
Console.WriteLine();
Console.WriteLine("MinSupportedDateTime=" + jpCal.MinSupportedDateTime.ToString());
Console.WriteLine();
// The first year of the Japanese calendar may begin on a day that is not January 1.
// Therefore, simple subtraction from the Western calendar may result in the wrong year.
// In JapaneseCalendar, GetEra,GetYear and IsLeapYear with two arguments give the correct result.
DateTime syouwa64 = new DateTime(1989, 1, 1);
DateTime heisei1 = new DateTime(1989, 1, 8);
DateTime heisei2 = new DateTime(1990, 1, 1);
DateTime heisei31 = new DateTime(2019, 4, 30);
DateTime reiwa1 = new DateTime(2019, 5, 1);
foreach (var dt in new[] { syouwa64, heisei1, heisei2, heisei31, reiwa1 })
{
string eraName = dt.ToString("gg y", jpCaulture).Split(" ")[0];
Console.WriteLine($"{dt:yyyy-MM-dd}, ERA={jpCal.GetEra(dt)}, {jpCal.GetYear(dt)}, EraName={eraName}");
}
}
}