在 Xamarin 表单中将 HijriCalendar 转换为 Gregorian

Converting HijriCalendar to Gregorian in Xamarin forms

我正在尝试在 Xamarin Forms 应用程序中将 HijriCalendar 转换为公历。然而,Xamarin Android 似乎对此并不满意。我还没有在 Xamarin iOS 中测试过它。 我使用的代码来自 无法从回历日期转换为公历日期 (c#) 并且在行

中实例化 HijriCalendar 对象时出现异常
DTFormat.Calendar = new System.Globalization.HijriCalendar(); //exception is thrown

{System.ArgumentOutOfRangeException: Not a valid calendar for the given culture. Parameter name: value at System.Globalization.DateTimeFormatInfo.set_Calendar (System.Globalization.Calendar value) [0x00142]

我已经检查了 解决方案,但这建议使用另一个我不感兴趣的库。 我已将 Android 项目中的链接属性更改为 None、仅限 Sdk Assemblyies 和 Sdk & User Assembly,但没有用。那么,如何将公历日期转换为 Xamarin 格式的回历日期?

我还在 Xamarin Android 的 OnCreate 方法中添加了以下代码来自 Thai crash: Not a valid calendar for the given culture

_ = new System.Globalization.GregorianCalendar();
_ = new System.Globalization.HijriCalendar();
_ = new System.Globalization.PersianCalendar();
_ = new System.Globalization.UmAlQuraCalendar();
_ = new System.Globalization.ThaiBuddhistCalendar();

我在这个 link 上发现了类似的问题 https://github.com/xamarin/Xamarin.Forms/issues/4037

// These classes won't be linked away because of the code,
// but we also won't have to construct unnecessarily either,
// hence the if statement with (hopefully) impossible
// runtime condition.
//
// This is to resolve crash at CultureInfo.CurrentCulture
// when language is set to Thai. See
// https://github.com/xamarin/Xamarin.Forms/issues/4037
if (Environment.CurrentDirectory == "_never_POSSIBLE_")
{
    new System.Globalization.ChineseLunisolarCalendar();
    new System.Globalization.HebrewCalendar();
    new System.Globalization.HijriCalendar();
    new System.Globalization.JapaneseCalendar();
    new System.Globalization.JapaneseLunisolarCalendar();
    new System.Globalization.KoreanCalendar();
    new System.Globalization.KoreanLunisolarCalendar();
    new System.Globalization.PersianCalendar();
    new System.Globalization.TaiwanCalendar();
    new System.Globalization.TaiwanLunisolarCalendar();
    new System.Globalization.ThaiBuddhistCalendar();
    new System.Globalization.UmAlQuraCalendar();
}

祝你好运!

尝试使用System.DateTime:

Calendar hijiri = new HijriCalendar();
DateTime date = new DateTime(1442, 4, 15, hijiri);
Console.WriteLine(date.Year); // 2020
Console.WriteLine(date.Month);//11
Console.WriteLine(date.Day); // 30


Calendar gregorian = new GregorianCalendar();
DateTime d = new DateTime(2020, 11, 30, gregorian);
var year = hijiri.GetYear(d);  //1442
var month = hijiri.GetMonth(d);  //4
var day = hijiri.GetDayOfMonth(d);  //15

另一种方法是使用 NodaTime.