Click here to Skip to main content
11,709,366 members (50,913 online)
Click here to Skip to main content

Convert date from Hijri Calendar to Gregorian Calendar and vise versa

, 20 Nov 2004 159.6K 3.3K 45
Rate this:
Please Sign up or sign in to vote.
In this class, I introduce a solution for converting dates between two calendars :Hijri & Gregorian.

Introduction

The main objective for this class is to convert between two calendars, the main advantage of this class is that it is very rich in overloaded function. So you can choose the best format you need.

Using the code

At the beginning, I defined variable cur of type System.Web.HttpContext. This variable will show any error happen during function execution but you have to turn Trace to true (in the ASP.NET page) in order to see error.

After that, I defined arCulture of type CultureInfo.

CultureInfo class represents information about specific culture, you have to specify this culture in the class constructor by giving the culture identifier. For e.g., "ar-SA" stands for Arabic-Saudi Arabia.

Also I defined h of type HijriCalendar. This variable represents instance of HijriCalendar class.

Now, how can I specify which calendar to use for a specific culture in case there is more than one calendar in one culture?

arCul.DateTimeFormat.Calendar=h;

Also, I declared an array allFormats, which contains the main possible formats for passed date, you can add your formats as well.

Where this array works?

When I am converting the string to DateTime format, I need to provide formats to match the string with the date.

DateTime tempDate=DateTime.ParseExact(hijri,allFormats,
          arCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);

There are two main functions in this class which are involved in converting dates:

public string HijriToGreg(string hijri)

You have to pass the Hijri date in string format, the returned string is equivalent Gregorian date and it will be in this format "yyyyMMdd", if you want another format then use the overloaded function and pass the format as second parameter.

The second function is:

public string GregToHijri(string greg)

This function is the opposite of the above one. Also it is overloaded for format.

Now for the rest of the class, I added additional functions which I think it's important in date manipulation, I provided each function with a small and easy to understand brief.

Deployment

You have to add this class to ASP.NET C# web project in order to compile correctly, then make an instance for this class in your ASP.NET page:

Dates d=new Dates();

Good luck.

////////////////////////////////////Attention///////////
///This library has been wrote by : Anas Reslan Bahsas
///if you are going to use it please dont remove this line .        
///you have to add this class to a asp.net web project to work well.
///I will be grateful to receive any commments or 
//suggestion to anasbahsas@hotmail.com
///////////////////////////////////////////////////////////
using System;
using System.Web;
using System.Diagnostics;
using System.Globalization;
using System.Data;
using System.Collections;

namespace Bahsas
{
    /// <summary>
    /// Summary description for Dates.
    /// </summary>
    public class Dates
    {
        private HttpContext cur;
        
        private const int startGreg=1900;
        private const int endGreg=2100;
        private string[] allFormats={"yyyy/MM/dd","yyyy/M/d",
            "dd/MM/yyyy","d/M/yyyy",
            "dd/M/yyyy","d/MM/yyyy","yyyy-MM-dd",
            "yyyy-M-d","dd-MM-yyyy","d-M-yyyy",
            "dd-M-yyyy","d-MM-yyyy","yyyy MM dd",
            "yyyy M d","dd MM yyyy","d M yyyy",
            "dd M yyyy","d MM yyyy"};
        private CultureInfo arCul;
        private CultureInfo enCul;
        private HijriCalendar h;
        private GregorianCalendar g;
            
        public Dates()
        {
            cur = HttpContext.Current;

            arCul=new CultureInfo("ar-SA");
            enCul=new CultureInfo("en-US");

            h=new  HijriCalendar();
            g=new GregorianCalendar(GregorianCalendarTypes.USEnglish);

            arCul.DateTimeFormat.Calendar=h;
            
        }
        
           /// <summary>
        /// Check if string is hijri date and then return true 
        /// </summary>
        /// <PARAM name="hijri"></PARAM>
        /// <returns></returns>
        public bool IsHijri(string hijri)
        {
            if (hijri.Length<=0)
            {
                
                cur.Trace.Warn("IsHijri Error: Date String is Empty");
                return false;
            }
            try
            {    
                DateTime tempDate=DateTime.ParseExact(hijri,allFormats,
                     arCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                if (tempDate.Year>=startGreg && tempDate.Year<=endGreg)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("IsHijri Error :"+hijri.ToString()+"\n"+
                                  ex.Message);
                return false;
            }

        }
        /// <summary>
        /// Check if string is Gregorian date and then return true 
        /// </summary>
        /// <PARAM name="greg"></PARAM>
        /// <returns></returns>
        public bool IsGreg(string greg)
        {
            if (greg.Length<=0)
            {
                
                cur.Trace.Warn("IsGreg :Date String is Empty");
                return false;
            }
            try
            {    
                DateTime tempDate=DateTime.ParseExact(greg,allFormats,
                    enCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                if (tempDate.Year>=startGreg && tempDate.Year<=endGreg)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("IsGreg Error :"+greg.ToString()+"\n"+ex.Message);
                return false;
            }

        }

        /// <summary>
        /// Return Formatted Hijri date string 
        /// </summary>
        /// <PARAM name="date"></PARAM>
        /// <PARAM name="format"></PARAM>
        /// <returns></returns>
        public string FormatHijri(string date ,string format)
        {
            if (date.Length<=0)
            {
                
                cur.Trace.Warn("Format :Date String is Empty");
                return "";
            }
            try
            {                       
                DateTime tempDate=DateTime.ParseExact(date,
                   allFormats,arCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                return tempDate.ToString(format,arCul.DateTimeFormat);
                            
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("Date :\n"+ex.Message);
                return "";
            }

        }
        /// <summary>
        /// Returned Formatted Gregorian date string
        /// </summary>
        /// <PARAM name="date"></PARAM>
        /// <PARAM name="format"></PARAM>
        /// <returns></returns>
        public string FormatGreg(string date ,string format)
        {
            if (date.Length<=0)
            {
                
                cur.Trace.Warn("Format :Date String is Empty");
                return "";
            }
            try
            {
                DateTime tempDate=DateTime.ParseExact(date,allFormats,
                    enCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                return tempDate.ToString(format,enCul.DateTimeFormat);
                            
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("Date :\n"+ex.Message);
                return "";
            }

        }
        /// <summary>
        /// Return Today Gregorian date and return it in yyyy/MM/dd format
        /// </summary>
        /// <returns></returns>
        public string GDateNow()
        {
            try
            {
                return DateTime.Now.ToString("yyyy/MM/dd",enCul.DateTimeFormat);
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("GDateNow :\n"+ex.Message);
                return "";
            }
        }
        /// <summary>
        /// Return formatted today Gregorian date based on your format
        /// </summary>
        /// <PARAM name="format"></PARAM>
        /// <returns></returns>
        public string GDateNow(string format)
        {
            try
            {
                return DateTime.Now.ToString(format,enCul.DateTimeFormat);
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("GDateNow :\n"+ex.Message);
                return "";
            }
        } 
        
        /// <summary>
        /// Return Today Hijri date and return it in yyyy/MM/dd format
        /// </summary>
        /// <returns></returns>
        public string HDateNow()
        {
            try
            {
                return DateTime.Now.ToString("yyyy/MM/dd",arCul.DateTimeFormat);
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("HDateNow :\n"+ex.Message);
                return "";
            }
        }
        /// <summary>
        /// Return formatted today hijri date based on your format
        /// </summary>
        /// <PARAM name="format"></PARAM>
        /// <returns></returns>

        public string HDateNow(string format)
        {
            try
            {
                return DateTime.Now.ToString(format,arCul.DateTimeFormat);
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("HDateNow :\n"+ex.Message);
                return "";
            }
            
        }
        
        /// <summary>
        /// Convert Hijri Date to it's equivalent Gregorian Date
        /// </summary>
        /// <PARAM name="hijri"></PARAM>
        /// <returns></returns>
        public string HijriToGreg(string hijri)
        {
            
            if (hijri.Length<=0)
            {
                
                cur.Trace.Warn("HijriToGreg :Date String is Empty");
                return "";
            }
            try
            {
                DateTime tempDate=DateTime.ParseExact(hijri,allFormats,
                   arCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                return tempDate.ToString("yyyy/MM/dd",enCul.DateTimeFormat);
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("HijriToGreg :"+hijri.ToString()+"\n"+ex.Message);
                return "";
            }
        }
        /// <summary>
        /// Convert Hijri Date to it's equivalent Gregorian Date
    /// and return it in specified format
        /// </summary>
        /// <PARAM name="hijri"></PARAM>
        /// <PARAM name="format"></PARAM>
        /// <returns></returns>
        public string HijriToGreg(string hijri,string format)
        {
            
            if (hijri.Length<=0)
            {
                
                cur.Trace.Warn("HijriToGreg :Date String is Empty");
                return "";
            }
            try
            {
                DateTime tempDate=DateTime.ParseExact(hijri,
                   allFormats,arCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                return tempDate.ToString(format,enCul.DateTimeFormat);
                
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("HijriToGreg :"+hijri.ToString()+"\n"+ex.Message);
                return "";
            }
        }
        /// <summary>
        /// Convert Gregoian Date to it's equivalent Hijir Date
        /// </summary>
        /// <PARAM name="greg"></PARAM>
        /// <returns></returns>
        public string GregToHijri(string greg)
        {
            
            if (greg.Length<=0)
            {
                
                cur.Trace.Warn("GregToHijri :Date String is Empty");
                return "";
            }
            try
            {
                DateTime tempDate=DateTime.ParseExact(greg,allFormats,
                    enCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                return tempDate.ToString("yyyy/MM/dd",arCul.DateTimeFormat);
                
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("GregToHijri :"+greg.ToString()+"\n"+ex.Message);
                return "";
            }
        }
        /// <summary>
        /// Convert Hijri Date to it's equivalent Gregorian Date and
     /// return it in specified format
        /// </summary>
        /// <PARAM name="greg"></PARAM>
        /// <PARAM name="format"></PARAM>
        /// <returns></returns>
        public string GregToHijri(string greg,string format)
        {
            
            if (greg.Length<=0)
            {
                
                cur.Trace.Warn("GregToHijri :Date String is Empty");
                return "";
            }
            try
            {
                
                DateTime tempDate=DateTime.ParseExact(greg,allFormats,
                    enCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                return tempDate.ToString(format,arCul.DateTimeFormat);
                
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("GregToHijri :"+greg.ToString()+"\n"+ex.Message);
                return "";
            }
        }
        
        /// <summary>
        /// Return Gregrian Date Time as digit stamp
        /// </summary>
        /// <returns></returns>
        public string GTimeStamp()
        {
            return GDateNow("yyyyMMddHHmmss");
        }
        /// <summary>
        /// Return Hijri Date Time as digit stamp
        /// </summary>
        /// <returns></returns>
        public string HTimeStamp()
        {
            return HDateNow("yyyyMMddHHmmss");
        }

                
        /// <summary>
        /// Compare two instaces of string date 
    /// and return indication of thier values 
        /// </summary>
        /// <PARAM name="d1"></PARAM>
        /// <PARAM name="d2"></PARAM>
        /// <returns>positive d1 is greater than d2,
    /// negative d1 is smaller than d2, 0 both are equal</returns>
        public int Compare(string d1,string d2)
        {
            try
            {
                DateTime date1=DateTime.ParseExact(d1,allFormats,
                    arCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                DateTime date2=DateTime.ParseExact(d2,allFormats,
                    arCul.DateTimeFormat,DateTimeStyles.AllowWhiteSpaces);
                return DateTime.Compare(date1,date2);
            }
            catch (Exception ex)
            {
                cur.Trace.Warn("Compare :"+"\n"+ex.Message);
                return -1;
            }

        }

        
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Anas Bahsas
Web Developer
Saudi Arabia Saudi Arabia
he is working now as Analyst Developer for Ebbon-Dacs, ,he implemnted projects for Goverment and Companys using C# , XML WebService , ASP.NET ,MSSQL 2000.

he also like to read about Security , Network programming specially in C#...

he is focusing now on software engineering and design patterns in C#.

You may also be interested in...

Comments and Discussions

 
QuestionThanks alot Pin
Rooka10-Jun-15 13:14
memberRooka10-Jun-15 13:14 
QuestionI used your class but with a change Pin
walcom28-Oct-13 1:10
memberwalcom28-Oct-13 1:10 
AnswerRe: I used your class but with a change Pin
OldTrain27-Apr-15 11:06
memberOldTrain27-Apr-15 11:06 
QuestionIs method Compare(string d1,string d2) work perfectly? Pin
houssam1135026-Sep-13 22:48
memberhoussam1135026-Sep-13 22:48 
QuestionExcellent work... Pin
Wael_Soltan23-Aug-13 1:08
memberWael_Soltan23-Aug-13 1:08 
GeneralMy vote of 5 Pin
mohamedenew25-Jan-13 22:44
membermohamedenew25-Jan-13 22:44 
GeneralRe: My vote of 5 Pin
JOSEPH B. MANLAPAZ27-Jun-13 5:48
memberJOSEPH B. MANLAPAZ27-Jun-13 5:48 
QuestionThank you, Pin
Reaper Liu16-Aug-12 5:30
memberReaper Liu16-Aug-12 5:30 
QuestionThank You Pin
Kushannc8-May-12 20:07
memberKushannc8-May-12 20:07 
QuestionThank you very much Pin
AhmedMido858-Apr-12 23:21
memberAhmedMido858-Apr-12 23:21 
GeneralThank you Pin
Member 829810412-Feb-12 18:45
memberMember 829810412-Feb-12 18:45 
GeneralMy vote of 5 Pin
eslam.badawy23-Oct-11 12:09
membereslam.badawy23-Oct-11 12:09 
Questionwrong calculation Pin
Abdul Sami_8-Oct-11 1:27
memberAbdul Sami_8-Oct-11 1:27 
Salam aliakum,

If you convert if from one date to another format it shows wrong calculated date. For example if today is 10 Zilqud, it will not show you this date on mentioning '10-08-2011'. It is showing a different date.
Abdul Sami

GeneralMy vote of 5 Pin
salemsalah27-Sep-11 5:43
membersalemsalah27-Sep-11 5:43 
GeneralMy vote of 4 Pin
e-life23-Jul-11 20:23
membere-life23-Jul-11 20:23 
QuestionNeed little help Pin
Beaudeep31-Oct-09 12:57
memberBeaudeep31-Oct-09 12:57 
AnswerRe: Need little help Pin
ashrafedes16-May-11 21:26
memberashrafedes16-May-11 21:26 
Generalit's a hack Pin
Anton Ponomarev2-Oct-08 22:52
memberAnton Ponomarev2-Oct-08 22:52 
GeneralThanx Pin
saud_a_k31-May-08 22:46
membersaud_a_k31-May-08 22:46 
GeneralUm Alqura Calendar Pin
WaleedH19-Mar-08 4:11
memberWaleedH19-Mar-08 4:11 
GeneralRe: Um Alqura Calendar Pin
Anas Bahsas19-Mar-08 21:48
memberAnas Bahsas19-Mar-08 21:48 
GeneralRe: Um Alqura Calendar Pin
WaleedH21-Mar-08 22:53
memberWaleedH21-Mar-08 22:53 
GeneralRe: Um Alqura Calendar Pin
Anas Bahsas21-Mar-08 23:04
memberAnas Bahsas21-Mar-08 23:04 
Generalthe conversion formula Pin
lantao7-Oct-07 16:01
memberlantao7-Oct-07 16:01 
GeneralRe: the conversion formula Pin
Anas Bahsas13-Nov-07 1:29
memberAnas Bahsas13-Nov-07 1:29 
GeneralRe: the conversion formula Pin
lantao3-Jan-09 11:08
memberlantao3-Jan-09 11:08 
GeneralRe: the conversion formula Pin
AJFK5-Aug-08 8:47
memberAJFK5-Aug-08 8:47 
GeneralRe: the conversion formula Pin
lantao3-Jan-09 11:13
memberlantao3-Jan-09 11:13 
GeneralGeneralize your class… Pin
mekki_ahmedi19-Apr-07 6:00
membermekki_ahmedi19-Apr-07 6:00 
GeneralRe: Generalize your class… Pin
Anas Bahsas13-Nov-07 1:27
memberAnas Bahsas13-Nov-07 1:27 
QuestionIn vc??? Pin
mohsen nourian17-Feb-07 22:36
membermohsen nourian17-Feb-07 22:36 
AnswerRe: In vc??? Pin
Anas Bahsas17-Feb-07 22:52
memberAnas Bahsas17-Feb-07 22:52 
Generaldfsv Pin
Anonymous25-Feb-05 20:36
sussAnonymous25-Feb-05 20:36 
GeneralHmmmm Pin
Patrik Svensson20-Nov-04 22:37
memberPatrik Svensson20-Nov-04 22:37 
GeneralRe: Hmmmm Pin
Anas Bahsas21-Nov-04 0:20
memberAnas Bahsas21-Nov-04 0:20 
GeneralRe: Hmmmm Pin
solo22-Nov-04 0:49
membersolo22-Nov-04 0:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 21 Nov 2004
Article Copyright 2004 by Anas Bahsas
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid