How to convert a Persian date into a Gregorian date?

Thanks guys,I used below code and my problem solved:

public static DateTime GetEdate(string _Fdate)
{
    DateTime fdate = Convert.ToDateTime(_Fdate);
    GregorianCalendar gcalendar = new GregorianCalendar();
    DateTime eDate = pcalendar.ToDateTime(
           gcalendar.GetYear(fdate),
           gcalendar.GetMonth(fdate),
           gcalendar.GetDayOfMonth(fdate),
           gcalendar.GetHour(fdate),
           gcalendar.GetMinute(fdate),
           gcalendar.GetSecond(fdate), 0);
    return eDate;
}

DateTime is always in the Gregorian calendar, effectively. Even if you create an instance specifying a dfferent calendar, the values returned by the Day, Month, Year etc properties are in the Gregorian calendar.

As an example, take the start of the Islamic calendar:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        DateTime epoch = new DateTime(1, 1, 1, new HijriCalendar());
        Console.WriteLine(epoch.Year);  // 622
        Console.WriteLine(epoch.Month); // 7
        Console.WriteLine(epoch.Day);   // 18
    }
}

It's not clear how you're creating the input to this method, or whether you should really be converting it to a string format. (Or why you're not using the built-in string formatters.)

It could be that you can just use:

public static string FormatDateTimeAsGregorian(DateTime input)
{
    return input.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss",
                          CultureInfo.InvariantCulture);
}

That will work for any DateTime which has been created appropriately - but we don't know what you've done before this.

Sample:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        DateTime epoch = new DateTime(1, 1, 1, new PersianCalendar());
        // Prints 0622/03/21 00:00:00
        Console.WriteLine(FormatDateTimeAsGregorian(epoch));
    }

    public static string FormatDateTimeAsGregorian(DateTime input)
    {
        return input.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss",
                              CultureInfo.InvariantCulture);
    }
}

Now if you're not specifying the calendar when you create the DateTime, then you're not really creating a Persian date at all.

If you want dates that keep track of their calendar system, you can use my Noda Time project, which now supports the Persian calendar:

// In Noda Time 2.0 you'd just use CalendarSystem.Persian
var persianDate = new LocalDate(1390, 7, 18, CalendarSystem.GetPersianCalendar());
var gregorianDate = persianDate.WithCalendar(CalendarSystem.Iso);

Tags:

C#