4

I searched and tried many examples unable to solve my hijri date is like,

19/07/1440

I tried this query

 SELECT TOP 200   
     DATEPART(YEAR, EndDateHejri)
 FROM 
     student

but I'm getting this error

Conversion failed when converting date and/or time from character string

I'm unable to solve error - hoping for your suggestions

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

4 Answers4

2

I bit of Google-Fu and format 131 should help you convert Hijri dates into Gregorian Dates...

DECLARE @hijri DATETIME = CONVERT(datetime, ' 7/05/1421 12:14:35:727PM', 131)

SELECT @hijri

Unfortunately, all the date functions (DATEPART(), DATENAME(), even DATEADD(), etc) are all based on manipulating Gregorian dates. So you can't use them.

So, you're forced to use string manipulation.

DECLARE @hijri DATETIME = CONVERT(datetime, ' 7/05/1421 12:14:35:727PM', 131)

SELECT @hijri

SELECT DATEPART(year, @hijri)
-- Gives 2000 :(

SELECT RIGHT(CONVERT(VARCHAR(10), @hijri, 131), 4)
-- Gives 1421 :)

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=901209ae0cdcf38cdcdea8afad4fd034

MatBailie
  • 83,401
  • 18
  • 103
  • 137
2

Posting a different answer. As the OP is only after the year part, and they've stated that it's always in the format 00/00/yyyy why not just use RIGHT? So:

SELECT RIGHT(EndDateHejri,4) as HejriYear;
Thom A
  • 88,727
  • 11
  • 45
  • 75
2

I tried answer @Vishnu Chandel it's working for me .

SELECT DATEPART(YEAR,CONVERT(datetime2(0),convert(VARCHAR,EndDateHejri),103)) 

And full code is :

SELECT TOP 200   
   SELECT DATEPART(YEAR,CONVERT(datetime2(0),convert(VARCHAR,EndDateHejri),103)) as year
 FROM 
     student
Abd Abughazaleh
  • 4,615
  • 3
  • 44
  • 53
1

Please try below code to get the correct output.

SELECT DATEPART(YEAR,CONVERT(datetime2(0),convert(VARCHAR,EndDateHejri),103));
Vishnu Chandel
  • 113
  • 2
  • 10