Is there any difference between DateTime in c# and DateTime in SQL server?
Precision and range (so, everything important ;-p)
From MSDN:
.NET System.DateTime
The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.)
Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calenda
Transact SQL datetime
Date Range: January 1, 1753, through December 31, 9999
Accuracy: Rounded to increments of .000, .003, or .007 seconds
How to compare sql datetime and c# datetime
You can use the SqlDateTime
structure.
DateTime now = DateTime.Now;
SqlDateTime sqlNow = new SqlDateTime(now);
bool equal = now == sqlNow.Value; // false
So if you have a DateTime
and want to know if it's equal to a DB-DateTime
use:
Assert.Equal(dbEndTime, new SqlDateTime(endTime).Value); // true
SqlDateTime
:
Represents the date and time data ranging in value from January 1,
1753 to December 31, 9999 to an accuracy of 3.33 milliseconds to be
stored in or retrieved from a database. The SqlDateTime structure has
a different underlying data structure from its corresponding .NET
Framework type, DateTime, which can represent any time between
12:00:00 AM 1/1/0001 and 11:59:59 PM 12/31/9999, to the accuracy of
100 nanoseconds. SqlDateTime actually stores the relative difference
to 00:00:00 AM 1/1/1900. Therefore, a conversion from "00:00:00 AM
1/1/1900" to an integer will return 0.
Difference between DateTime formats in Database and Dataset
row["DO_Date"].ToString()
returns a string which depends on your local system regional datetime setting.
Try doing the following:
DateTime dt = DateTime.ParseExact(row["DO_Date"].ToString("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
In other words - force the source format to be the same as the one you are trying to convert to.
There is a simpler way though:
DateTime dt = (DateTime)row["DO_Date"]
SQL server DateTime and C# DateTime
The DateTime, which is represented by the string, isn't supported by the calender.
This error is being given because your C# application views the date 2012-14-10
as saying the 14th
month, 10th
day, and 2012th year
. The day and year work find, but the month doesn't. Further, don't try and change how your C# application views the date, that's based off the culture of the system.
You're confusing how to define a DateTime
object and how to display one.
Since you're storing your date as a DateTime
in SQL, there's not a good reason for me to believe that you would need to do any kind of parsing. Consider the below code sample.
var dataTable = new DataTable();
var dataAdapter = new SqlDataAdapter("SELECT * FROM YourTable", "{connection string}");
dataAdapter.Fill(dataTable);
var yourDate = dataTable.Rows[0]["Date"]; <=== the type will be DateTime, simple.
Adding Parameters
Let's take your example query:
"SELECT * FROM date_test WHERE id = '4' AND date BETWEEN '" + dt1 + "' AND '" + dt2 + "'";
And let's fix it a bit, consider the below example:
var dataTable = new DataTable();
var dataAdapter = new SqlDataAdapter("SELECT * FROM date_test WHERE id = @ID AND date BETWEEN @StartDate AND @EndDate", "{connection string}");
dataAdapter.SelectCommand.Parameters.AddWithValue("@ID", "4");
dataAdapter.SelectCommand.Parameters.AddWithValue("@StartDate", new DateTime(2012, 10, 1));
dataAdapter.SelectCommand.Parameters.AddWithValue("@EndDate", new DateTime(2012, 10, 14));
dataAdapter.Fill(dataTable);
var yourDate = dataTable.Rows[0]["Date"]; <=== the type will be DateTime, simple.
datetime in C# vs, SQL and GETDATE() from SQL Server
DateTime
in .Net framework and SQL Server (if it is DateTime type field) is irrespective of the format. Format is only useful for displaying output.
If your field in SQL Server is of DateTime
type then you can query it from C# code using parameterized query something like:
public DataTable GetRecords(DateTime dtParameter)
{
DataTable dt = null;
using (SqlConnection conn = new SqlConnection("connection string"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * from yourTable where DateField = @dateparameter"))
{
conn.Open();
cmd.Parameters.AddWithValue("@dateparameter",dtParameter);
SqlDataReader dr = cmd.ExecuteReader();
//...rest of the code
dt.Load(dr);
}
}
return dt;
}
Comparing SQL datetime to C# DateTime.Now
Instead of converting the current date to a string and then using TimeSpan.Parse()
, you should use the TimeOfDay
property as it already returns a TimeSpan
:
string startingtime = cmdx.ExecuteScalar().ToString();
var u1 = DateTime.Now.TimeOfDay;
var u2 = TimeSpan.Parse(startingtime);
Console.WriteLine(u1 - u2);
Then, comparing the difference in time against a certain threshold should be the way to go. You may use something like this:
TimeSpan diff = u1 - u2;
if (diff.TotalSeconds > 60)
{
// Call your method here.
}
Moreover, depending on the type of your column in the database, you might not need to call .ToString()
and parse the result. If it's a date type, something like this could work:
var u2 = ((DateTime)cmdx.ExecuteScalar()).TimeOfDay;
Otherwise, if it's a string column, then TimeSpan.Parse(startingtime)
would be fine.
Day Date difference between two date calculation in SQL AND C# producing varying result
The TimeSpan.Days
property returns whole days only, dropping any fractional portion. Depending on the time portion of your two DateTime
's, you could expect the behavior you're seeing.
Try taking the time portion out of the equation by using the Date
property (and effectively setting both times to midnight):
diffdays = (EndDate.Date - StartDate.Date).Days
Alternatively, you can round up the TotalDays
property (which includes fractional portions of days):
diffdays = Math.Ceiling((EndDate - StartDate).TotalDays);
DateTime2 vs DateTime in SQL Server
The MSDN documentation for datetime recommends using datetime2. Here is their recommendation:
Use the
time
,date
,datetime2
and
datetimeoffset
data types for new
work. These types align with the SQL
Standard. They are more portable.
time
,datetime2
anddatetimeoffset
provide more seconds precision.
datetimeoffset
provides time zone
support for globally deployed
applications.
datetime2 has larger date range, a larger default fractional precision, and optional user-specified precision. Also depending on the user-specified precision it may use less storage.
Related Topics
How to Catch All Exceptions/Crashes in a .Net App
What Is a Regular Expression for Parsing Out Individual Sentences
Mixed Mode Assembly Is Built Against Version 'V1.1.4322'
Newtonsoft JSON.Net Serialize Jobject Doesn't Ignore Nulls, Even with the Right Settings
C# Datagridview Checkbox Checked Event
Better Way to Cast Object to Int
How to Set the Color of a Selected Row in Datagrid
Put Content in Httpresponsemessage Object
Declaration of Anonymous Types List
Sending Windows Key Using Sendkeys
How to Bring Up the Built-In File Copy Dialog
How to Show the "Open With" File Dialog
Entity Framework. Delete All Rows in Table