How to convert Gregorian to Hijri using C#

In this article, we will develop a small C# program that converts an input date from the Gregorian format to the Hijri format.

History

Before we get into coding, let's briefly understand the Gregorian and Hijri calendars.

The Gregorian calendar is the most used calendar worldwide. It was introduced in October 1582 by Pope Gregory XIII, with the purpose of replacing the Julian calendar. By doing this, we would have years with a duration in days as close as possible to the one computed for the Solar years.

The Hijri calendar, also known as the Muslim calendar or Islamic calendar, is a lunar calendar that was created around 622 A.D.

Code example

The code below executes the date conversion to the target format, given a date expressed in the Gregorian form.

Note: To help in the date conversion, we use the behavior defined in the built-in UmAlQuraCalendar class, on which the date conversion logic is already implemented.

using System;
using System.Globalization;
class Program {
public static DateTime GregorianToHijriDateConversion(DateTime gregorianDate)
{
Calendar umAlQura = new UmAlQuraCalendar();
var hijriYear = umAlQura.GetYear(gregorianDate);
var hijriMonth = umAlQura.GetMonth(gregorianDate);
var hijriDay = umAlQura.GetDayOfMonth(gregorianDate);
Console.WriteLine($"Hijri Date (day/month/year): {hijriDay}/{hijriMonth}/{hijriYear}");
return new DateTime(hijriYear, hijriMonth, hijriDay);
}
public static void Main (string[] args) {
Console.WriteLine("***** First Example *****");
//Expected result (day/month/year): 24/06/1449
Program.GregorianToHijriDateConversion(new DateTime(2027, 11, 23));
Console.WriteLine("***** Second Example *****");
//Expected result (day/month/year): 20/12/1466
Program.GregorianToHijriDateConversion(new DateTime(2044, 11, 10));
}
}

Code example

  • Lines 1–2: We import relevant namespaces.

  • Line 6: We declare the method that contain our algorithm. This method has one input parameter, which is the Gregorian date.

  • Line 8: We instate an object from the UmAlQuraCalendar, which help in the conversions.

  • Line 9: We extract the Hijri date year from the Gregorian date.

  • Line 10: We extract the Hijri date month from the Gregorian date.

  • Line 11: We extract the Hijri date day from the Gregorian date.

  • Line 12: We write the converted date in the format day/month/year to the console.

  • Line 13: The method returns the converted date in the Hijri format.

  • Lines 19 and 22: We call the date conversion algorithm using two different Gregorian input dates.

Free Resources