As you know PCL doesn't support PersianCalendar or GregorianCalendar class, So I'm using generic to achieve that, In this case consumer can pass the Calendar to the class:
public class DateConvertor<TCalendar> where TCalendar : Calendar
{
public DateConvertor()
{
this.CurentCalendar = Activator.CreateInstance<TCalendar>();
}
public TCalendar CurentCalendar
{
get;
private set;
}
public DateTime GetDate(string date)
{
//....
var newDate = new DateTime(year, month, day, hour, minute, 0);
return newDate;
}
}
So I need pass a new instance of PersianCalendar to DateTime's constructor:
var newDate = new DateTime(year, month, day, hour, minute, 0, new PersianCalendar());
Now my question is that How can I do that? For example something like this:
var newDate = new DateTime(year, month, day, hour, minute, 0, CurentCalendar);
Can I pass a generic type as a parameter to DateTime's constructor?
Update:
It seems that DateTime class doesn't have that signature for accepting a new instance of Calendar in Portable Class Library:
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second,
Calendar calendar
)
As you've noted, DateTime
doesn't have the constructor you want in the PCL. However, you can use Calendar.ToDateTime
:
return CurrentCalendar.ToDateTime(year, month, day, hour, minute, 0, 0);
As an aside, you could change your generic constraint to include new()
, and just call the constructor:
public class DateConverter<TCalendar> where TCalendar : Calendar, new()
{
public DateConverter()
{
this.CurrentCalendar = new TCalendar();
}
}
Or use my Noda Time project which supports other calendars in a rather more pleasant way, IMO - e.g. a LocalDateTime
"knows" the calendar it belongs to, and allows you to convert to a LocalDateTime
in another calendar, etc.
See more on this question at Stackoverflow