Suppose we have a given DateTime variable something like :
DateTime BirthDate{get;set;}
and different users/clients set this variable according to their preferred calendar (in our case Georgian
, Hijri
and Persian Calendar
) and we want to save all dates in Gerogian
presentation so that we can save them in Microsoft SQL Server.
The question is if there is a way to find out the calendar of a given date so that we can convert it from its original calendar to Georgian Canlendar
?
No, DateTime
doesn't retain calendar information... it's effectively always in the Gregorian calendar. If you construct a DateTime
with a different calendar system, it converts it to the Gregorian calendar, and you need to use the Calendar
methods to get back to the original values. So you need to store the calendar system separately, basically. That could be part of the client configuration, by the sounds of it.
For example:
Calendar hebrewCalendar = new HebrewCalendar();
DateTime today = new DateTime(5775, 5, 18, hebrewCalendar);
Console.WriteLine(today.Year); // 2015
Console.WriteLine(hebrewCalendar.GetYear(today)); // 5775
On the other hand, if you were to use my Noda Time project, there the appropriate types do retain calendar system information - as well as generally being clearer about the difference between instants, local dates, local times etc. Obviously I'm biased, mind you :)
Noda Time equivalent of the above (using 2.0 as it's slightly simpler!)
using System;
using NodaTime;
class Test
{
static void Main()
{
var hebrewCalendar = CalendarSystem.HebrewCivil;
var today = new LocalDate(5775, 5, 18, hebrewCalendar);
Console.WriteLine(today.Year); // 5775
Console.WriteLine(today.WithCalendar(CalendarSystem.Gregorian).Year); // 2015
}
}
See more on this question at Stackoverflow