How to save Hijri dates (0000/01/01-9999/01/01) in Microsoft SQL Server tables? What type of column?
I choose datetime2, is it right?
CRE
Store them in datetime2 -- they should go in as utc dates. If you have strings, convert them using CONVERT passing the style code 131.
DECLARE @HijriDateString VARCHAR(10) = '02/02/1435';
declare @HijriDate datetime2 = CONVERT(DATETIME, @HijriDateString, 131);
declare @FormattedOuput varchar(255) = convert(nvarchar(255), @HijriDate, 131);
select @HijriDateString as [original string], @HijriDate as [parsed datetime2], @FormattedOuput as [formatted output]
-- original string parsed datetime2 formatted output
-- 02/02/1435 2013-12-05 00:00:00.0000000 2/02/1435 12:00:00.0000000AM
Then when you present the date to the user, you format it back out as Hijri.
By keeping it in datetime2, you can do proper date arithmetic, using things like
MyDateColumn < getutcdate()
To do correct comparisons.
EDIT for @Dotctor's question Does a normal grouping by day not work? There's every chance I'm missing something key, so I'd be glad to learn
begin tran
create table #hijriDateExample (id int, d datetime2)
insert into #hijriDateExample values
(1, CONVERT(DATETIME, '02/02/1435 01:00' , 131)),
(2, CONVERT(DATETIME, '02/02/1435 22:00' , 131)),
(3, CONVERT(DATETIME, '03/02/1435 04:00' , 131))
select dateadd(DAY,0, datediff(day,0, d)), count(*) as [numberOfDays] from #hijriDateExample
group by dateadd(DAY,0, datediff(day,0, d))
-- 2013-12-05 00:00:00.000 2
-- 2013-12-06 00:00:00.000 1
rollback tran