Ali_Nass
Ali_Nass

Reputation: 928

Passing dates from db RESTful web API Best Practices

So I have 2 types of dates in my db, date (yyyy-mm-dd) and datetimeoffset (yyyy-mm-ddThh:mm:ss.ms+Z), and I was wondering what is the best practice to deal with it when I'm taking the data from the DB and passing it as a json to the UI/mobile.

I used to always parse dates to datetimeoffset so normal dates will be something like 2018-09-24T00:00:00.000+00:00 instead of simply 2018-09-24 but it works perfectly with datetimeoffset that are already saved like that in the DB

Upvotes: 1

Views: 2261

Answers (2)

Arunprasanth K V
Arunprasanth K V

Reputation: 21931

In multiple ways you can handle this situation.

1 : From API side always give predefined date format value

Example yyyy-mm-ddThh:mm:ss.ms+Z

And from the client side based on conditions you can convert it.

2: Keep different View models/ Properties may be for storing yyyy-mm-dd you can give string data type and for yyyy-mm-ddThh:mm:ss.ms+Z just DateTime . and based on your db you can write a condition and map the particular data.

3: Keep a single property for returning the date and make it as string

Example : Public string CurrentDate{get;set;} and you can simply map the database values(Conversion should be done). In this case client no need to worry about the date conversions they can simply show what ever you are passing from the api.

Note : The method 3 is not preferable because in the case in some places the user may see yyyy-mm-dd in some other places yyyy-mm-ddThh:mm:ss.ms+Z.

Upvotes: 1

Zohar Peled
Zohar Peled

Reputation: 82514

Take a look at SQL Server Data Type Mappings
You will see that SQL Server's Date, DateTime and DateTime2 all map to .Net's DateTime data type,
and DateTimeOffset maps to DateTimeOffset.

SQL Server Database Engine type             .NET Framework type
date (SQL Server 2008 and later)            DateTime
datetime                                    DateTime
datetime2 (SQL Server 2008 and later)       DateTime
datetimeoffset (SQL Server 2008 and later)  DateTimeOffset

Upvotes: 0

Related Questions