How to set PersianCalendar to CultureInfo
This project contains a solution for set PersianCalendar to CultureInfo.


Introduction

The Calendar property of DateTimeFormatInfo accepts only calendars that are valid for the culture associated with this instance of DateTimeFormatInfo. For example, if the current instance originated from the DateTimeFormatInfo property of a "fa-Ir" CultureInfo object, this property can accept only the calendars that are valid for the "fa-Ir" culture. The CultureInfo.Calendar property specifies the default calendar (GregorianCalendar) for the culture and the CultureInfo.OptionalCalendars property specifies all calendars supported by the culture (GregorianCalendar and HijriCalendar).
.Net framework doesn’t support Persian calendar for the culture. This culture doesn’t accept the calendar; therefore display of DateTime in this culture is impossible.
Somebody present useful solutions to solve it. These solutions usually based on declare new type same as PersianDate and something like that. This type wraps DateTime. Developers should be used it without functionalities of DateTime and other classes depend on it. Therefore I present a solution to solve these problems.

Background

For set calendar to culture, the OptionalCalendars of it should be have specified calendar. In Persian Culture this calendar doesn’t exists. This code raises exception:
//this code raises exception
info.DateTimeFormat.Calendar = new PersianCalendar();

Using the code

Use PersianCultureHelper to set Persian calendars same as:

//create an instance of culture
CultureInfo info = new CultureInfo(“fa-Ir”);

//set Persian option to specified culture
PersianCultureHelper.SetPersianOptions(info);

This class set an instance of PersianCalendar to specified culture with using reflection. It finds private fields of the culture and its DateTimeFormatInfo and set correct values to them. With this solution you don’t need a new version of DateTime.
By this solution you achieve two advantages:

• You can work with DateTime and display it without getting exception.

untitled.JPG

• You can enable .net framework futures for the culture same as change asp .net calendar functionality like as:

untitled1.JPG

You can install “Persian Culture Package.msi” and write this code:

// create an instance of culture
CultureInfo info = new CultureInfo(“fa-Ir”);
//set Persian calendar to it without get exception
info.DateTimeFormat.Calendar = new PersianCalendar();

This setup enables .net framework’s custom culture only with copy fa-IR.nlp file to %SystemRoot%\Globalization. You can get more information about create custom culture from Msdn.

Last edited Jan 30, 2009 at 2:50 PM by rezataroosheh, version 5