DateTimePicker c# only works with Months - c#

Help as early as possible please
I have a form in which I add Exhibitions in the museum name, the date through the Datetimepicker and people came up and then they are saved in the sql database And then on another form I want to select 2 dates in two Datetimepickers and to show in the datagrid that there are some exhibitions between two dates BUT it does not show me correctly, I can not even explain whats wrong
private void button3_Click(object sender, EventArgs e)
{
string period = "SELECT* FROM vistavka WHERE Date BETWEEN '" + dateTimePicker1.Value.ToString() + "' AND '" + dateTimePicker2.Value.ToString() + "'";
LoadData(period);
dataGridView2.Columns[0].Visible = false;
/*dataGridView2.Columns[1].Visible = false*/;
dataGridView2.AllowUserToAddRows = false;
button1.Enabled = true;
}
is it right?
i want it show like events between 12.November.2020 and 21.December.2020

I think you can just use the answer from this question here.
Basically, you just need to feed it the proper format:
string period = "SELECT* FROM vistavka WHERE Date BETWEEN '" + dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss.fff") + "' AND '" + dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
For bonus points you could also switch to using string interpolation to make it more readable.
string period = $"SELECT* FROM vistavka WHERE Date BETWEEN '{dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")} ' AND '{dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")} '";
Update:
Please check out this on why doing it this way is a security problem.
Then learn about SQL parameters here.
And finally you can see this answer for how to do date parameters. Basically, you shouldn't have to convert a C# datetime to a string just to pass it into SQL. C# already has mechanisms for this and for good reason, as you'll see in those links.

the date to string convertion was used is wrong
"SELECT* FROM vistavka WHERE Date BETWEEN '" + dateTimePicker1.Value.ToString() + "' AND '" + dateTimePicker2.Value.ToString() + "'";
ToString() format is culture depended and should not be used
You have to pass SQL query with parameters and parameter values (as DateTime objects) to convert date from DateTime by SQL client API to the parameter value format used by your SQL server.
Please find MS SQL sample here

Related

DateTime Conversion Issue From LocalTime to UTC while saving in db on Published site

I am trying to save a DateTime to a database.
When I run the code from my server machine and save the date to the db, it saves the DateTime correctly, but when I deploy the site to production, access it from my local machine, and try to save the same DateTime, then it changes it to a diferent date and time. I guess this may be due to diferent timezones on my machine and the server machine.
I tried to convert the datetime to UTC but its not working:
DateTime OnlyStartDate = Convert.ToDateTime(app_date);
DateTime NewStartDateTime = Convert.ToDateTime(
OnlyStartDate.Add(TimeSpan.Parse(appData.start.ToString("HH:mm:ss"))));
startTime = Convert.ToString(NewStartDateTime);
This is the query in which the variable startTime is passed, which saves the wrong time to the db:
query = "Insert into [Appointments] Values('" + loc_id + "', '" + appData.titleId +
"', '" + patiant_id + "', '" + app_date + "', '" + startTime + "', '" + endTime +
"', '" + appData.providerId + "', 'enable', 'False', '" + userEmail + "', '" +
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "', '" + userEmail + "', '" +
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "', '" +
appData.statusId + "', '" + appData.userId + "','')";
DB.executeQuery(query);
Working with DateTimes is tricky and there are rules that you should follow to ensure that the system behaves as expected.
Always transmit the UTC value of a DateTime.
Always transmit the value of a DateTime using ISO8601 notation if the serialization of the instance occurs using a string representation. Sending DateTime using json or in a query string in a URL are both examples where this should be done.
Always store DateTime instances using the UTC value.
Always store DateTime instances using a native type in the persistence store (never as string).
When sending DateTime values from the client convert to a UTC value as early as possible as the client "knows" about it's relevant time zone.
When sending DateTime values from the server to the client convert to the local time zone as late as possible on the client as the client "knows" about it's relevant time zone.
When displaying a DateTime value convert to a string (from DateTime type) as late as possible in the call stack (ie. it is a presentation layer concern best handled by the client).
When sending a DateTime value from the client back to the server convert to a DateTime type as early as possible.
When creating ado.net commands/queries (regardless of the underlying provider) always use parameters for all values and in the parameter:
specify the matching Db value type
assign the native value (not the string representation)
For sql-server specific example using c# see How can I add user-supplied input to an SQL statement?
Use DateTime.UtcNow when saving data into db, on display convert it to the timezone you want to display datetime with, this is the main practice initially.
example for displaying UTC datetime in Jordan timezone:
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Jordan Standard Time");
string CreatedDate = TimeZoneInfo.ConvertTimeFromUtc(model.CreatedDate, timeZoneInfo).ToString("d/M/yyyy HH:mm:ss")
model.CreatedDate is a UTC datetime from db.

Send only date and not time to date field in sql

I'm trying to update a DATE (not DATETIME) column in SQL Server, but when I execute the SQL command, it is posted with time format also.
string datetosql = "10.4.2015";
string sqlQuery = "UPDATE tbl_tasks " +
"SET description = '" + tbTaskDescription.Text + "', " +
"deadline = '" + datetosql + "' , " +
"status = '" + statusIndex.ToString() + "' " +
"WHERE tid = " + _TaskID;
When I later collect the date using SqlDataReader, it is posted with time format: 04.10.2015 00:00:00. Why is this happening?
.NET doesn't have a date only data type.
If you ask to return a SQL Server date, or a time, it always returns a DateTime struct instance in .NET. For a date, the time properties (hours, minutes, etc.) will be 0.
Note that using queries that aren't parameterized is considered bad! You are open for SQL injection, and you make your life harder since you need to escape quotes, etc.
Add a cast to datetosql, ex:
Cast(datetosql as Date)

How to insert datetimepicker default value to MYSQL with datetime column type?

I have 2 project, one is CRUD class and another is contain a WinForm that will access the CRUD class.
Here come my problem, everytime i trying to insert DateTimePicker with default value in MYSQL with datetime column type, i getting 0000-00-00 00:00:00 Zero zero zero and zero value, what i missed here?
Here is my part of CRUD class code, my CRUD class named DBConnect.cs
public DateTime property_dtDate { get; set; }
sqlQuery = "INSERT INTO master (NoInvoice, Name, Date, Type, Additionaltext) VALUES ('" + property_NoInvoice + "', '" + property_sName + "', '" + property_dtDate + "', '" + property_sType + "', '" + property_sAdditionalText + "')";
And here is my part of WinForm code, which is i named it Form1.cs (both is in separated project)
clsDbConnect.property_dtDate = DateTime.Parse(datetimepicker1.Value.ToString("yyyy-MM-dd HH:mm:ss"));
clsDbConnect.Insert();
I try look at the value with messagebox, a value that pass through my WinForm is good, nothing suspicious, it show the every date and time which is right know, but when i looked in my database, all i got is 0000-00-00 00:00:00. I don't have any clue what cause that, help me to find out please
I think you have a problem because of string format of the datetime. MySQL not understand your string format as a datetime value.
Try use parameters(assume somewhere in code you have a SqlCommand object):
string query = "INSERT INTO master (NoInvoice, Name, Date, Type, Additionaltext) VALUES (#NoInvoice, #sName, #dtDate, #sType, #sAdditionalText)";
using(SqlCommand command = New SqlCommand(query, yourconnection)
{
command.Parameters.AddWithValue("#NoInvoice", property_NoInvoice);
command.Parameters.AddWithValue("#sName ", property_sName);
command.Parameters.AddWithValue("#dtDate ", property_dtDate);
command.Parameters.AddWithValue("#sType ", property_sType);
command.Parameters.AddWithValue("#sAdditionalText ", property_sAdditionalText);
command.ExecuteNonQuery();
}
Using parameters help with type safety(datetime and numerics format issues) and prevent a SQL injection vulnerability.
Then when you don't need to parse a datetimepicker's value to type DateTime because ti is already DateTime (From MSDN: DateTimePicker.Value)
clsDbConnect.property_dtDate = datetimepicker1.Value;

Create a appended string with separating date time with date in javascript

I am doing something to prepare a string to display in a format in server side but now I have to replace it in javascript so my server side code is:
DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[0];
string time = now.GetDateTimeFormats('t')[0];
txtFileName.Value = someString.Length > 10 ? someString.Substring(0, 10).TrimEnd() + "_" + date + "_" + time : someString.TrimEnd() + "_" + date + "_" + time;
txtFileName.Value = txtFileName.Value.Replace(' ', '_');
How to achieve that?
Although JavaScript provides a bunch of methods for getting and setting parts of a date object, it lacks a simple way to format dates and times according to a user-specified mask.
Check these date function and follow following links:
Formatting a date in javascript
How can I convert string to datetime with format specification in JavaScript?
var d = new Date();
var datepart = d.getDate() + " " + d.getMonth() + " " + d.getFullYear();
using Date object same you can create time format also.
To create filename format use javascript replaceenter link description here method
var myNewString = myOldString.replace("username", visitorName);
Check this to create trim method or extend javascript String Object
Hope this is enough to convert your server side code in java script...
check out DateJS, it has very powerfull date manipulation functions

QUERY ON DATES TO EXCEL USING C#

I was trying to make excel graphs using query in c# and I need to collect data for the last month. I am using the following code and its not giving any error but its not giving any result either.
Basicaly I have the data in excel sheets and using that data im making graphs.
First im geting the two dates and converting them to short string and then im matching the strings with the dates picked from excel in the short strong format.
If anyone could answer, I would really appreciate help.
Thankyou,
THE CODE:
// Get current date and time
DateTime dtx = DateTime.Now;
string Date = dtx.ToShortDateString();
// Calculating the last month's date (substracting days from current date.)
DateTime lastmonth= DateTime.Today.AddDays( -30 );
string Date2 = lastmonth.ToShortDateString();
OleDbCommand objCmdSelect = new OleDbCommand(
"SELECT [Hour],(Format(Date, 'Short Date')) AS text_Date,[U_CSSR] FROM [" + excelSheets[j] + "] WHERE CI=" + id + " AND (Format(Date, 'Short Date'))BETWEEN "+ Date + " AND "+ Date2 + " ", objConn);
I think your WHERE clause is logically incorrect. it should be
... BETWEEN "+ Date2 + " AND "+ Date ...
The earlier date should come first.
BETWEEN a AND b is equal to: x > a and x < b.

Categories