Adding time to SQL date query - c#

var datadb1 = DateTime.ParseExact(dateTimePicker1.Text, "dd/MM/yyyy", null);
var timedb1 = DateTime.ParseExact(dateTimePicker2.Text, "HH:mm:ss", null);
var datadb2 = DateTime.ParseExact(dateTimePicker3.Text, "dd/MM/yyyy", null);
var timedb2 = DateTime.ParseExact(dateTimePicker4.Text, "HH:mm:ss", null);
commanddb.CommandText =
"SELECT * FROM testtab WHERE datatime >= #from and datatime < #to";
commanddb.Parameters.AddWithValue("#from", datadb1);
commanddb.Parameters.AddWithValue("#to", datadb2);
Need to add time check to this query (I`m getting time info from dateTimePicker2 and dateTimePicker4).

Need to add time check to this query
The problem with your code is that you are passing only the date part to check to the SQL query. In order to make your query check both the date and time parts, you have to:
Declare the SQL parameters of data type datetime(SqlDbType.DateTime).
The value you are passing to the sql parameter should be of data type DateTime and contains both parts the date and time parts.
One way to achieve this is by using the same DateTimePciker to pass both date and time parts, then don't use the datetimepicker Text property and use DateTimePicker.Value property instead, it will give you both date and time parts:
SqlParameter fromParam= new SqlParameter("#from", SqlDbType.DateTime);
fromParam.Value = dateTimePicker1.Value;
SqlParameter toParam= new SqlParameter("#to", SqlDbType.DateTime);
toParam.Value = dateTimePicker2.Value;
commanddb.Parameters.Add(fromParam);
commanddb.Parameters.Add(toParam);
Or, by adding both the date part and time part coming from different datetimepickers to the same DateTime variable before passing it to the sql parameter. Something like this:
var datadb1 = DateTime.Parse(dateTimePicker1.Value.ToShortDateString());
var timedb1 = DateTime.Parse(dateTimePicker2.Value.ToShortTimeString());
DateTime datetimeCombined1 = datadb1 + new TimeSpan(timedb1.Hour,
timedb1.Minute,
timedb1.Second);
Then you have to pass this variable datetimeCombined1 to the SQL parameter, the same with the second datetime range, you have to combine both the parts before passing it.
This is assuming that you are using dateTimePicker1 to read the date part only and the dateTimePicker2 to read the time part only.

If you want to use each dateTimePicker for Date or Time seperatly you can define a DateTime variables and Set its Date value and Time Value like this:
DateTimePicker dateTimePickerFromDate = new DateTimePicker();
DateTimePicker dateTimePickerFromTime = new DateTimePicker();
DateTimePicker dateTimePickerToDate = new DateTimePicker();
DateTimePicker dateTimePickerToTime = new DateTimePicker();
DateTime fromDateTime = new DateTime(dateTimePickerFromDate.Value.Year,
dateTimePickerFromDate.Value.Month, dateTimePickerFromDate.Value.Day,
dateTimePickerFromTime.Value.Hour, dateTimePickerFromTime.Value.Minute,
dateTimePickerFromTime.Value.Second);
DateTime toDateTime = new DateTime(dateTimePickerToDate.Value.Year,
dateTimePickerToDate.Value.Month, dateTimePickerToDate.Value.Day,
dateTimePickerToTime.Value.Hour, dateTimePickerToTime.Value.Minute,
dateTimePickerToTime.Value.Second);
commanddb.CommandText =
"SELECT * FROM testtab WHERE datatime >= #from and datatime < #to";
commanddb.Parameters.AddWithValue("#from", fromDateTime);
commanddb.Parameters.AddWithValue("#to", toDateTime);

Related

How to add date parameter and time now to Entity Framework?

I have a string date parameter as 04/14/2018, and I want to add parameter with this date and time now to field datetime in Entity Framework. As sample
string value_date = '04/14/2018' ;
add.Order_Date = Convert.ToDateTime(value_date);
db.Products(add);
db.SaveChanges();
It's working, the data in database save as 2018-04-14 00:00:00 (the column Order_Date in database with type smalldatetime). If to get date and time now, easy to do this with DateTime.Now (it'll get value date and time as 2018-04-13 09:15:00). So, I want to get date parameter with time now, as sample 2018-04-14 09:15:00. How can I do that ?
Just get TimeOfDay and add to your date.
add.Order_Date = Convert.ToDateTime(value_date).Date.Add(DateTime.Now.TimeOfDay);
You can simply construct a new DateTime object using the order date and the current time.
var orderDate = Convert.ToDateTime("04/14/2018");
var accurateDate = new DateTime(
orderDate.Year,
orderDate.Month,
orderDate.Day,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second);

Date Time Picker Comparison not displaying values

In my MySQL database, I am using a DATETIME type to log events. The format is yyyy-MM-dd HH:mm:ss
I am trying to use a Windows Form to display events from a particular range. However, I am not receiving any values with my query. I tried a simple select * and that worked, but not when I tried to use parameters. This is what I have thus far. I know I am very close, just missing something small, I suspect:
String query = "SELECT Device FROM log WHERE Stamp >= #p_StartDate AND STAMP <= #p_EndDate;
OdbcCommand command = new OdbcCommand(query, myConnection);
command.Parameters.AddWithValue("#p_StartDate", fromDate.Value); // name of dateTimePicker
command.Parameters.AddWithValue("#p_EndDate", endDate.Value); // name of dateTimePicker2
OdbcDataAdapter adp = new OdbcDataAdapter(command);
DataSet set = new DataSet();
adapter.Fill(set);
dataGridView1.DataSource = set.Tables[0];
My Date Time Pickers have a Custom Format of yyyy-MM-dd HH:mm:ss as well so the DateTime should match up but they don't seem to, for some reason.

How to get short date format from the datetime object

I am capturing the time in the text box (by using AJAX calender extender)
the time in the string is 12/10/2013, but when I assign the string to a datetime object it is converted into 12/10/2013 12:00:00 AM.
I want to use the date to filter the records in the database using the query below. Please help
string date1 = txtDate1.Text;
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName,Story.StoryId,COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=" + date1 + "
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC ;";
It's generally not a good idea to pass dates as strings in your queries because you will most likely run into formatting issues - leave it up to the Framework you are using decide on what the best format is.
In your circumstances, you can do this by using SqlParameters e.g.
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName, Story.StoryId, COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=#dateTime
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC";
using (SqlConnection connection = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand(strQuery, connection))
{
cmd.Parameters.AddWithValue("#dateTime", date);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
}
}
Another important reason to use parameters when writing raw SQL is to ensure your user input is correctly sanatized and safe to pass to the DB. Failure to do this can leave you open to various exploitations such as SQL Injection.
Instead of DateTime object you can use Date object.
DateTime is an integer interpreted to represent both parts of DateTime (ie: date and time). You will always have both date and time in DateTime.
ex:
DateTime.Now.ToString("MM/dd/yyyy");

SQL error converting data type datetime to smalldatetime?

In my SQL stored procedure:
#StartDate as smalldatetime,
#EndDate as smalldatetime
In my C# code:
StartDate = new DateTime(1901,01,01,00,00,00);
EndDate = new DateTime(2200,01,01,00,00,00);
var StartDate2 = StartDate.ToString("dd/MM/yyyy HH:mm:ss");
StartDate2 = DateTime.ParseExact(StartDate2, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy HH:mm:ss");
StartDate = Convert.ToDateTime(StartDate2);
var EndDate2 = EndDate.ToString("dd/MM/yyyy HH:mm:ss");
EndDate2 = DateTime.ParseExact(EndDate2, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy HH:mm:ss");
EndDate = Convert.ToDateTime(EndDate2);
The column is as a smalldatetime type in the db. I'm going round in the circles with this! whats the correct way to parse my Dates to the correct format for querying in the db?
UPDATE:
Changed code to this and worked fine.
SqlParameter parameter = daHoliday.SelectCommand.Parameters.Add("#StartDate", System.Data.SqlDbType.SmallDateTime);
SqlParameter parameter2 = daHoliday.SelectCommand.Parameters.Add("#EndDate", System.Data.SqlDbType.SmallDateTime);
parameter.Value = StartDate;
parameter2.Value = EndDate;
Don't convert them to string, just pass them as DateTime type object through Command Parameters.
DateTime should never be converted to string to match format of data in database table. If the datatype in table is DateTime then its always better to pass the .Net framework DateTime object as parameter to command.

format string in datetime c# to insert in MYSQL datetime column

I have code like this:
AutoParkDataDataContext Db = new AutoParkDataDataContext();
Dailyreport dailyRep = new Dailyreport();
string time = Convert.ToDateTime("10-10-2014 15:00:00");
dailyRep.order_time = time;
Db.Dailyreports.InsertOnSubmit(dailyRep);
Db.SubmitChanges();
When I see it in the DailyReport table it shows me only the date ("10-10-2014 00:00:00:00"), so the time is ignored. How could i fix it?
The column type is DateTime.
A quick/easy method to insert date or datetime into MySQL is to use the format 'yyyy-MM-dd', or datetime as 'yyyy-MM-dd H:mm:ss'.
Try this
DateTime theDate = DateTime.Now;
theDate.ToString("yyyy-MM-dd H:mm:ss");
Make your SQL look like this.
insert into mytable (date_time_field) value ('2013-09-09 03:44:00');
Your line:
string time = Convert.ToDateTime("10-10-2014 15:00:00");
Shouldn't compile.
I can only guess that you don't have DateTime as type of your column in SQL Server, you should modify it to keep DateTime and then pass a DateTime type object, not a string.
This means that the underlying data type in the database must be Date. Change that to DateTime and it will store the time as well.
DateTime dateTimeVariable = DateTime.Now;
string date = dateTimeVariable.ToString("yyyy-MM-dd H:mm:ss");
The insert Statement will look kind of like this:
string InsertQuery = "INSERT INTO table( `fieldName` ) VALUES ( '" + date + "' )";

Categories