How to save Hijri dates in sql server tables? What type of column?

后端 未结 4 829
无人及你
无人及你 2021-01-18 18:21

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         


        
4条回答
  •  情书的邮戳
    2021-01-18 18:43

    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
    

提交回复
热议问题