In past projects, I tried to save my time format in Gregorian dates and convert Gregorian dates to Persian in the logic layer of application, but I'm tired of doing it in that way.
I need save and restore date time with format of Persian in sql server without any conversion
Can type of datetime2 in sql server store Persian date time?
If not, what is the best way to store Persian date time?
datetime2
in SQL Server uses the Gregorian calendar.If you want to use dates based on the Persian calendar, then you either need to make and use some functions that you can call in your SQL code to do the conversion for you, or you need to make a User Defined Type that can store the data.
Here's an example of some functions that can convert between Persian and Gregorian. I haven't tried them out so I have no idea if they work, or to their quality.
I couldn't find an example of creating a UDT for Persian dates, but this is the documentation for UDTs in general.
Personally, I would store the dates in SQL Server as UTC Gregorian
datetime2
. And I'd either have conversion code in the application data layer that converts them when saving to, and loading from SQL Server, or I'd do the conversion when theDateTime
is displayed to/retrieved from the user.UTC is the date and time standard for the world, especially for science and engineering, and as such SQL Server and .Net have been built using it. It makes sense to also use UTC so that you can get the most benefit from the existing SQL Server and .Net code. Of course your users still want to be able to write and read a
DateTime
using the Persian calendar, so it makes sense to me that you'd perform that conversion just before one will be displayed to the user, or just after the user has provided one.You can use in SQL SERVER 2016 above Persian format like this function :
You can use directly in query for change date to Persian like this :
I hope you wish the best
You can use the below functions to convert calendar to Persian and vice versa.
and the second function is:
Example of using this function is:
Result is: