Passing dates from db RESTful web API Best Practices - c#

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

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.

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

Related

Convert from UTC C# SQL

Using a combination of server-side C#, SQL database, and the dayjs client-side library dayjs I am unable to convert the date stored as UTC in the database UTC to local time.
My theory is to store all date-times in the database as UTC. Use the client (browser) to determine the user timezone (automatically or store it for each user), then let the browser, via dayjs convert from UTC time to local time.
This is NOT a dayjs problem but the way dates are stored in SQL and pulled via C#.
In order for dayjs to convert the DateTime on the client app the date must be returned from the server in a very specific format.
If you are using DateTime C# and SQL datatypes and using just pulling the DateTime straight from the database to a DTO the date will be returned to the client like this:
noteDate: "2022-01-06T22:31:34.81"
In order for dayjs.tz() method to work the date DateTime must be returned from the server in this format:
noteDate: "2022-01-06T22:31:34.81Z"
Then this code will property convert from UTC to local time:
let date = "2022-01-06T20:14:18.917Z";
let timeZoneGuess = dayjs.tz.guess();
date = dayjs(date).tz(timeZoneGuess);
To get this format to the client I had to add additional information to the DateTime before returning the note.NoteDate to the client.
note.NoteDate = DateTime.SpecifyKind(note.NoteDate, DateTimeKind.Utc);
When storing the DateTime in SQL I am using c# DateTime and SQL DateTime datatypes. When setting the note.NoteDate I call note.NoteDate = DateTime.UtcNow but apparently SQL does not save the "Z" part of the UTC date.
I would like to see if anyone else has this same issue and if there are better ways to solve it.

Datetime format is 'mm-dd-yyyy' when getting while using SqlDataAdapter but if I run the same query in ms sql then its 'yyyy-mm-dd'

I know the question is a bit confusing. Please let me elaborate.
Suppose
I have a table student master which has a column DOB
I have inserted a record and in DOB I have inserted '1991-01-01'
running select statement from sql server is returning date in the same format as it is inserted '1991-01-01' but when I am running the same query from C# using SqlDataAdapter then its returning date as '01-01-1991'
Can anyone explain why it is happening and is there any way to fetch the date in same format as it is inserted.
Query
Is it possible to get the DateTime using SqlDataAdapter as it was inserted?
P.S: column data type is Datetime
let's separate the wheat from the chaff :)
if for your needs meaningful is data type (datetime in this case), then formatting does not matter at all. All layers which will exchange or process the data will use data type information for that.
But
if the meaningful part is formatting, i.e. string representation of the data, then you need to consider the appropriate settings of UI tools you use to display your data. SSMS, for example, uses regional settings for that. If you need to visualize data in the identical manner, so you need the identical strings, you should take care of formatting by your self or in another words, you need to convert your datetime data to string in the same way in all places where you need it.
In T-SQL, for example, you could use CAST and CONVERT functions for formatting your data in a format you need.
If you can't match up the "Cultures" between the SQL Server and the machine you're building the application on (and, in fact, you cannot rely on that really if you're application is going to be deployed to other machines!), then the cheap and quick way round it is to run your date returns through a parse function such as this:
private string FncFormatDate(string date)
{
DateTime formattedDate;
if (DateTime.TryParse(date, out formattedDate))
{
return formattedDate.ToString("yyyy-MM-dd");
}
else
{
return "Invalid date";
}
}
I hope this answers your question.

Different format for timestamp when using c# datareader

I'm reading a timestamp from a mysql table using an OdbcDataReader. When I look at the data in the table it is in the format 2013-09-12 11:11:09. But the reader seems to read it in the format 12/09/2013 11:11:09.
I then try to insert this into another mysql table but receive the error:
Incorrect datetime value: '12/09/2013 11:11:09' for column 'timestamp'
at row 1
How can I sort out this difference in formatting? Should I be referencing some Unix timestamp value somehow?
The data shouldn't be in the table in any text format. It's just a date and time.
You'll see the format when you convert the data to a string - which you should do as rarely as possible. In particular, when you're inserting the data into a different table, you shouldn't use a formatted value at all - you should use a DateTime in parameterized SQL.
Basically, unless you really need a string representation of the data, you should keep it in the "native" representation (DateTime in this case). Every time you have a conversion to or from text, that's an opportunity for failure. Dates and times are hard enough with time zones etc, without extraneous conversions getting involved.
How are you looking at the data "in the table"? I'm not familiar with the MySQL implementation, but with Oracle and Sql Server datetime values are stored in an unreadable binary format, and translated to a readable timestamp by the query tool. MySQL is likely doing something similar.
try to insert this into another mysql table
If you care about format when you're inserting the data, you're doing something really bad. That's a strong indication you're using a technique that will be vulnerable to sql injection attacks, rather than parameterized queries. If you use parameterized queries, you assign a C# datetime type to the query parameter value directly, and the ADO.Net object handles any formatting you need. At that point, anything you can successfully DateTime.Parse() or DateTime.TryParse() becomes a valid input for your query.

How can i set sql date time with entity framework c#.net

I am very new to entity framework. Nice concept and fast as well.
Working in c#.net right now. I have stucked here where datetime comes in picture.
I mean....
lets assume i have user table in DB where CreatedDate fields is there in with datetime datatype in sql db.
My entity framework works like this...
when i need to add object to db, i simply pass objUser.createdDate = DateTime.now.
How ever I want to change the concept for some requirement changes.
I need to store sql server DateTime() for createdDate field in table.
How can i do that???
any idea...please help.
follwoing is a just sample code of my project.
objCustomer.RegisterDate = DateTime.Now;
objCustRepository.AddCustomer(objCustomer);
I want to remove this DateTime.Now line and maintain through sql....
if you can store the value from stored procedure instead of your business logic then you can try it by following.
to store SQL Datetime value then you can also use GETDATE() function in SQL.
or
you can define RegisterDate default value = GETDATE()
It sounds like you are trying to target the specific timezone associated with your sql server, if I am not mistaken?
If so why not use DateTimeOffset.Now via your c# when setting the date.
See this blog post here about the type.
A DateTimeOffset represents a specific point in time, so you can use it to convert to any timezone representation you may need on your UI.
Be aware though that it is only supported on SQL Server 2008 and greater, if I remember correctly. :)

How to change date format in mysql stored procedure insert statement "22-12-2010" to "2010-12-22"

I send the registration date parameter to mysql database like "22-12-2010". But my sql date date type is in another format how can I change the date format like "2010-12-22" also I have to insert this into table.
Give code in C#,asp.net code behind either sql query statement!
Use this comprehensive MSDN pages as your guide: Standard Date and Time Format Strings and Custom Date and Time Format Strings.
There are many examples on those pages on how to reformat a date string in C#, and they also provide a good clear explanation on how date formatting works in the DateTime class.
Once you've reformatted your date string in C#, you should be able to pass it on down without needing to use SQL to reformat it.

Categories

Resources