Compare datetime column with datetime variable in asp.net sql where clause - c#

I have a column named compare_time(datatype: DateTime) in database. Its value is inserted as 3/8/2017 12:09:08 AM. Now in c# I want to write a query to compare if this column value is equal to Singapore's current date time.(Only need to compare the date.). Current Singapore date time is get as 08-03-2017 PM 03:35:11.
TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
DateTime dt = Convert.ToDateTime(singaporetime); //08-03-2017 PM 03:35:11.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM time_details where compare_time='"+dt+"' ", con1);
Please help to correct the where clause.

The first step is to not compare the dates using automatic string conversion but use a parameter.
Still this is not enough because your DateTime variable contains also the time part as well the database column. So you need to isolate the date part both on the database data and in the variable
DateTime dt = Convert.ToDateTime(singaporetime); //08-03-2017 PM 03:35:11.
SqlDataAdapter adapter = new SqlDataAdapter(#"SELECT * FROM time_details
where Convert('Date',compare_time) = #date", con1);
adapter.SelectCommand.Parameters.Add("#date", SqlDbType.DateTime).Value = dt.Date;
....
In this way you don't let the compiler decide which is the right string 'format' that is correct for Sql Server to understand your query.
Instead you pass the DateTime variable as a Date (using the Today property which doesn't have a meaningful time part) to the database engine that now has all the info to make the correct comparison.
Notice that this approach could not be the most efficient one. That CONVERT inside the WHERE clause could wreak havoc with your indexes. Probably you could use a different approach
string cmdText = #"SELECT * FROM time_details
where compare_time >= #init AND
compare_time < #end";
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, con1);
adapter.SelectCommand.Parameters.Add("#init", SqlDbType.DateTime).Value = dt.Date;
adapter.SelectCommand.Parameters.Add("#end", SqlDbType.DateTime).Value = dt.Date.AddDays(1);

Related

How to extract specific DATE and TIME from resulted MySQL query in C#?

I want to extract DATE and TIME into two different variables that can be used to display in text boxes.
Here is what I am doing in my code -
MySqlCommand cmd3 = new MySqlCommand();
MySqlDataReader reader2 = null;
cmd3.CommandText = "SELECT lastlogintime from authentication where email=#email";
cmd3.Parameters.AddWithValue("#email", LoggedInUser);
cmd3.Connection = connect;
reader2 = cmd3.ExecuteReader();
while (reader2.Read())
{
string temp = reader2.GetString(reader2.GetOrdinal("lastlogintime"));
lastloginDateTB.Text = temp.ToString(); // This will give full string as (yyyymmdd HH:mm:ss) into lastloginDateTb
// Now I want to display date in Date_TB and Time in Time_TB. Note: I have 2 different textboxes as lastloginDateTB & lastloginTimeTB ;
}
This code extract value from authentication table (lastlogintime column) into temp variable and displays the same in lastloginDateTB textbox but I want to display specific date and time in each of its column.
Note: Table consist of fieldname - lastlogintime which has DATETIME value.
Simply convert the string to DateTime and extract date using ToShortDateString() method and Time using ToShortTimeString() method
Try this:
DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");
dt.ToString("HH:mm");
dt.ToString("hh:mm tt");
dt.ToString("H:mm");
dt.ToString("h:mm tt");
string date = dateTime.Date.ToString(); //for date

Conversion failed when converting date and/or time from character string SQL in c#

I get this error when I compare to dates.
sql query command :
Select * from processTBL WHERE is=2016144 and date between '10/06/2016' and '15/06/2016'
that command work but when Fill Data to DateTabe I get converting error.
That's my c# method;
public DataGridView hesapOzeti(string command)
{
DataGridView gdview = new DataGridView();
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlCommand komut = new SqlCommand(command, connection);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
gdview.DataSource = dt;
return gdview;
}
The Error:
A quick fix would be to send dates in an unambiguous format, so that your format is properly interpreted:
Select * from processTBL WHERE is=2016144 and date between '20160601' and '20160616'
The error comes from the fact that 15 is considered a month and thus the date is unparsable.
The correct way of doing it is to use a parameterized query:
command.Parameters.AddWithValue("#is", 2016144);
command.Parameters.AddWithValue("#FromDate", new DateTime(2016, 06, 10));
command.Parameters.AddWithValue("#ToDate", new DateTime(2016, 06, 15));
Your query becomes:
Select * from processTBL WHERE is = #is and date between #FromDate and #ToDate
Generally speaking, you should always try to use parameterized queries to avoid such errors and protect against SQL injection.
The date format for literals is dependant upon the locale (specifically the DATEFORMAT). The BOL page for datetime lists the locale and non-locale specific formats
https://msdn.microsoft.com/en-AU/library/ms187819.aspx
Ideally, you should use the ISO 8601 format - YYYY-MM-DDThh:mm:ss[.mmm] or
YYYYMMDD[ hh:mm:ss[.mmm]]
In your code, try date between '20160610' and '20160615'

How to access data from sql server 2008 table of a specific date in c#?

In my window application I want to show records held between two dates. I used datepicker to select dates. In sql server 2008 table I used data type [date] to store date. My problem is that it is not working properly to catch the first date, it catches next date to which I select. I used following code :
cmd5.Parameters.AddWithValue("date1", dateTimePicker4.Value);
cmd5.Parameters.AddWithValue("date2", dateTimePicker5.Value);
and when I try this :
cmd5.Parameters.AddWithValue("date1", dateTimePicker4.Value.AddDays(-1));
cmd5.Parameters.AddWithValue("date2", dateTimePicker5.Value);
Result-
my complete code
cmd10 = new SqlCommand("select a_id,commtyp,convert(varchar(10),date,105),comm,primm,c_id,agent from comm where a_id= '" + textBox1.Text + "' AND date >= #date1 AND date <= #date2 ", agr);
cmd10.Parameters.AddWithValue("#date1", dateTimePicker1.Value.AddDays(-1));
cmd10.Parameters.AddWithValue("#date2", dateTimePicker2.Value);
adp = new SqlDataAdapter(cmd10);
DataSet ds = new DataSet();
adp.Fill(ds, "comm");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "comm";
checkBox2.Checked = false;
groupBox15.Show();
cmd10.Parameters.Clear();
You are using value property from datepicker and it's giving you date with seconds and milliseconds. You have to get the actual datepart from it's value.
try this
dateTimePicker4.Value.Date
instead of
dateTimePicker4.Value
you are taking datetime picker and in query may be you are taking from and to dates as datetime.
pleases convert #from and #to datetime in to date as
cast(#From as date)
cast(#To as date)
and then put into condition, it may resolve your problem..

use session variables as parameters in asp.net

I have to following parameters that are necessary to execute a stored procedure in sql server 2008 r2
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate.ToString());
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate.ToString());
da.SelectCommand.Parameters.AddWithValue("#PaymentType", payment.ToString());
These are necessary to execute a stored procedure. All of the session variables are passed correctly. However when the gridview renders it shows no data. I know there is data because I can run the stored procedure on SSMS and it runs perfectly with the parameters that are passing to the proc (when I input them).
I am pretty confused at this point so any help would be helpful.
grdDenialDetail.DataSource = ds.Tables["DetailDenial"].DefaultView;
grdDenialDetail.DataBind();
ENTIRE ROUTINE: (maybe this will help)
public void ExecuteDetailReport()
{
string sessionConnection = Session["Company"].ToString();
string sessionStartDate = Session["StartDate"].ToString();
string sessionEndDate = Session["EndDate"].ToString();
string payment = Session["payment"].ToString();
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings[sessionConnection].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("dbo.cusGenDenialReportPivotStylePType", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
/*da.SelectCommand.Parameters.Add(new SqlParameter("#StartDate", SqlDbType.VarChar, 11)).Value = sessionStartDate.ToString();
da.SelectCommand.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.VarChar, 11)).Value = sessionEndDate.ToString();
da.SelectCommand.Parameters.Add(new SqlParameter("#PaymentType", SqlDbType.VarChar, 100)).Value = payment.ToString();*/
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate);
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate);
da.SelectCommand.Parameters.AddWithValue("#PaymentType", payment);
lblTest.Visible = true;
lblTest.Text = "You selected " + payment + ".";
DataSet ds = new DataSet();
da.Fill(ds, "DetailDenial");
grdDenialDetail.DataSource = ds.Tables["DetailDenial"].DefaultView;
grdDenialDetail.DataBind();
da.Dispose();
conn.Close();
}
I think your issue is related to the fact that you are using and comparing dates as strings and not dates. Your result set is empty because your query is trying to compare date strings alphabetically instead of chronologically. To refactor your code, I would make sure that you address the following areas:
Setting the session variables
Carefully parse the dates out of your text fields.
DateTime startDate;
if (DateTime.TryParseExact(txtStartDate.Text, "MM/dd/yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out startDate))
{
Session["StartDate"] = startDate;
}
DateTime endDate;
if (DateTime.TryParseExact(txtEndDate.Text, "MM/dd/yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out endDate))
{
Session["EndDate"] = endDate;
}
You may want to handle the case when the TryParseExact methods return false (parse failure).
Retrieving session variables
We set the session variables as DateTime objects, so cast them back upon retrieval:
var sessionStartDate = (DateTime)Session["StartDate"];
var sessionEndDate = (DateTime)Session["EndDate"];
Notice we're still using native .NET types here.
Setting up your query parameters
Use the .Date property of the DateTime struct to drop the time component:
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate.Date);
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate.Date);
...
And lastly, update your stored procedure so that its parameters are of type date:
CREATE PROCEDURE dbo.cusGenDenialReportPivotStylePType
(
#StartDate date = null,
#EndDate date = null,
...
)
AS
...
SELECT
*
FROM
Somewhere
WHERE
TheDate BETWEEN #StartDate AND #EndDate
Keeping everything in its native data format will make your life a lot easier.
Remove .ToString() calls from your code.

How to run query on date time colomn

Trying to retrieve records by passing date in where condition, i am sending date by using date time picker but at the end reader not showing any record.
I did conversion of date time as Convert(char(10),ext_date,101) still facing the same problem.
string str=#"select * from extra_expense where CONVERT(char(10),ext_date,101) = #date";
sqlcommand = new SqlCommand(str,sqlconnection );
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetimepicker1.value);
datareader = sqlcommand.ExecuteReader();
List<Projects> projects = new List<Projects>();
while (datareader.Read())
{
Projects proj = new Projects();
proj.expenseid = Convert.ToInt32(datareader.GetValue(0));
proj.ProjectDate = Convert.ToDateTime(datareader.GetValue(1));
projects.Add(proj);
}
datareader.Close();
return projects;
You can specify dates as strings in T-SQL, like so:
SELECT MyFields FROM MyTable
WHERE StartDate >= '01-01-00' AND StartDate <= '12-31-00'
You shouldn't cast the field in the table, you should cast the parameter to the correct type. In fact, you are already casting it because the parameter is declared as datetime, but on your query you are forcing ext_date to char(10).
Try this:
string str=#"select * from extra_expense where ext_date = #date";
along with
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetime.Parse( datetimepicker1.value);

Categories

Resources