13

如何在日历之间转换?这是我所拥有的:

UmAlQuraCalendar hijri = new UmAlQuraCalendar();
GregorianCalendar cal = new GregorianCalendar();

DateTime hijriDate = new DateTime(1434, 11, 23, hijri);
DateTime gregorianDate = ...; //

我需要一个gregorianDate对应于hijriDate.

4

3 回答 3

18

ADateTime可以在其构造函数中使用替代日历接受输入,但在内部它始终使用公历等价形式存储。所以你已经有了你要找的东西。

Calendar umAlQura = new UmAlQuraCalendar();
DateTime dt = new DateTime(1434, 11, 23, umAlQura);

// As a string, it will format with whatever the calendar for the culture is.
Debug.WriteLine(dt.ToString("d", CultureInfo.InvariantCulture)); // 09/29/2013
Debug.WriteLine(dt.ToString("d", new CultureInfo("ar-SA")));     // 23/11/34

// But the individual integer properties are always Gregorian
Debug.WriteLine(dt.Year);  // 2013
Debug.WriteLine(dt.Month); // 9
Debug.WriteLine(dt.Day);   // 29

换个方向,您必须使用日历对象上的方法获取部件。

DateTime dt = new DateTime(2013, 9, 29);  // Gregorian

Calendar umAlQura = new UmAlQuraCalendar();

Debug.WriteLine(umAlQura.GetYear(dt));       // 1434
Debug.WriteLine(umAlQura.GetMonth(dt));      // 11
Debug.WriteLine(umAlQura.GetDayOfMonth(dt)); // 23
于 2013-09-29T20:13:53.303 回答
8

似乎保存的日期DateTime始终在当前日历中。因此,如果当前日历是公历hijriDate,则已经是公历。

var hijriDate = new DateTime(1434, 11, 23, hijri);
//Console writeline will show 2013-09-29 00:00:00

如果您当前的日历是UmAlQuraCalendar您应该能够使用以下方法提取公历日期:

var hijri = new UmAlQuraCalendar();
var cal = new GregorianCalendar();

var hijriDate = new DateTime(1434, 11, 23, hijri);
var y = cal.GetYear(hijriDate), 
var m = cal.GetMonth(hijriDate), 
var d = cal.GetDayOfMonth(hijriDate)
于 2013-09-29T08:18:23.300 回答
2

作为扩展方法

public static DateTime GregorianToUmAlQura(this DateTime gregorianDate)
{
    Calendar umAlQura = new UmAlQuraCalendar();

    return new DateTime(umAlQura.GetYear(gregorianDate), umAlQura.GetMonth(gregorianDate), umAlQura.GetDayOfMonth(gregorianDate), umAlQura);
}
于 2018-02-01T15:13:13.647 回答