Pregunta

I have an application where I use the Gregorian calendar with DateTime. Lately, I decided to make the app use the Julian calendar too, if the user demands it (there are still people using this calendar). Things seemed pretty easy at first. I could specify the used calendar in the DateTime constructor:

var calend = new JulianCalendar();
DateTime dt = new DateTime(year, j, i, calend);

I could get the number of days in each month and the day of the week (that seems to be different from the Gregorian calendar!):

int days = calend.GetDaysInMonth(year, month);
DayOfWeek dayOfWeek = dt.DayOfWeek;

Now, what amazed me and troubled me was whe output of DateTime.ToString(). It seems that it prints the date in the Gregorian calendar:

http://msdn.microsoft.com/en-us/library/system.globalization.juliancalendar%28v=vs.71%29.aspx

Currently, the JulianCalendar is not used by any of the cultures supported by the CultureInfo class; therefore, this class can only be used to calculate dates in the Julian calendar.

http://msdn.microsoft.com/en-us/library/9bksd5y7.aspx

Because the Persian calendar cannot be designated as the default calendar for a culture, displaying a date in the Persian calendar requires individual calls to its PersianCalendar.GetMonth, PersianCalendar.GetDayOfMonth, and PersianCalendar.GetYear methods.

So, what's the easiest way to print a date in the Julian calendar?

¿Fue útil?

Solución

Using an extension method:

static class JulianPrinter
{
    public static string ToString(this DateTime date, string format, CultureInfo ci, Calendar cal)
    {
        if (format == "D")
            return string.Format("{0}, {1} {2} {3}",
                ci.DateTimeFormat.GetDayName(cal.GetDayOfWeek(date)),
                cal.GetDayOfMonth(date),
                ci.DateTimeFormat.MonthGenitiveNames[cal.GetMonth(date) - 1], //ci.DateTimeFormat.GetMonthName(cal.GetMonth(date)),
                cal.GetYear(date));
        return "";
    }
}

...and :

var calend = new JulianCalendar();
DateTime dt = new DateTime(year, j, i, calend);
string printed = dt.ToString("D", ci, calend);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top