datetime format in ASP.NET C# not recognized - c#

I have a column in my database with the following content:
status
2018-12-31 15:31:56.000 (result of a select in SMSS)
I am trying to get this column's data in ASP.NET code behind page through a query in C#:
var connectionString = System.Configuration.ConfigurationManager.AppSettings["connection"];
SqlConnection con = new SqlConnection(connectionString);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 [status] from [tablename] where idNo = '" + idNo+ "'", con);
con.Open();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Debug.WriteLine("\n Rows extracted."); // -> Error thrown here.
Debug.WriteLine("\n Rows content:" + DateTime.ParseExact(dt.Rows[0][0].ToString(), "yyyy-MM-dd hh:mm:ss.000", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None));
con.Close();
da.Dispose();
}
No matter what I try I always get either
String was not recognized as a valid DateTime
or the datetime is not recognized as part of the Gregorian calendar.
I have tried to display the dt.Rows[0][0] content directly, but then I get an error about the date not being in the Gregorian calendar.
Are there any steps I could undertake to understand what is going on with this?
Working with DateTime is an absolute nightmare in C#, I wished MS would finally fix this.
Please don't point me to the docs or other articles, that's obviously where I come from...

Case is important when it comes to format strings. See: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
The string you actually want is:
yyyy-MM-dd HH:mm:ss.fff
Note the case of Months, Hours and minutes.
h = 12 hour clock, H = 24 hour clock.
Demo
Now you just need to adopt best practices for calling the database. Use parameterised queries and read up on using statements

You should use MM(uppercase) which means month and the mm(lowercase) is minute.
if (dt.Rows.Count > 0)
{
Debug.WriteLine("\n Rows extracted."); // -> Error thrown here.
Debug.WriteLine("\n Rows content:" + DateTime.ParseExact(dt.Rows[0][0].ToString(), "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None));
con.Close();
da.Dispose();
}
NOTE: Please DON'T concatenate data in your query, That will be the invitation to the hacker for SQL injection. Use parameterized queries instead
More info : https://stackoverflow.com/a/7505842/2131576

Related

Is there any way that l can retrieve all record of any month of the year from SQLDatabase C#

I have succeeded in getting all record of sales transaction for today on just clicking a button. Below is my codes
con.Open();
string query = "select Date Transactioncode, Productname, Total FROM Stock WHERE Date >= CAST(GETDATE() AS DATE) ORDER BY Date DESC";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
SDA.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
The problem I am having is how to get all sales transaction for the month or any month and year that i wish to search. I am using 2 comboBoxes to select month and year in order to get records from the SQLDatabase. Below the codes i had tried which kept producing error.
con.Open();
string query = "SELECT * FROM Stock WHERE Month(Date) = '"+comboMonth.Text+"' AND Year(Date) = '"+comboYear.Text+"'";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
SDA.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
this is the error i got: Conversion failed when converting the varchar value 'January' to data type int"
kindly help please
I would do this on the SQL side, as there are functions there to render date in any form, which you can compare to. It might not make for the most efficient query.
Either rendering the date as a string would allow use of 'like' and an index (I always liked the ISO YYYY-MM-DD HH:MM:SS.ssssss), or indexing the function expression is also allowed now.
For just one year one month, you should calculate the first and last second/day of date-times and do a range scan on the date-time value, which is both more efficient and non-hash (ordered) index friendly. Some Date types are of day granularity, some are date-time. https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-ver15 And of course the exact ends of days vary with Daylight Savings and the like, a real mess doing queries by shift on 3 shifts a day!

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

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);

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..

How to Convert date into dd.MM.yyyy format in C# from excel

In excel sheet i have date in format dd.MM.yyyy 16.10.2011 (16 as dd, 10 as MM). When i'm importing data from excel to SQL Server 2008 i get MM.dd.yyyy but still 16.10.2011 (16 as MM, 10 as dd). That's not correct. I found solution on this: go to SQL Server 2008 -> Security -> logins -> {user properties} -> and change default language for user. With this solution i get in SQL Server 2008 dd.MM.yyyy 16.10.2011 (16 as dd, 10 as MM). Is there any other way to convert date in dd.MM.yyyy format without changing user language?
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\JantarV7Export.xlsx;Extended Properties=Excel 8.0";
OleDbConnection olecon = new OleDbConnection(sConnectionString);
olecon.Open();
OleDbCommand cmd = olecon.CreateCommand();
cmd.CommandText = "SELECT person_id, date_of_hours, number_of_hours FROM [Sheet1$]";
OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
OleDbDataReader odr = cmd.ExecuteReader();
conn.Open();
while (odr.Read())
{
SqlCommand cmd1 = conn.CreateCommand();
cmd1.CommandText = "INSERT INTO test_data values (newid(),'" + odr[0] + "',#date_of_hours,'" + odr[2] + "')";
cmd1.Parameters.Add("#date_of_hours", SqlDbType.DateTime).Value =odr[1];
}
cmd1.ExecuteNonQuery();
olecon.Close();
conn.Close();
I think that problem is when i'm inserting into test_data datatable. So i probably should convert dates somehow before inserting. What do you suggest? Thanks. Is there any options like this:
cmd1.CommandText = "INSERT INTO test_data values (newid(),'" + odr[0] +
"',CONVERT(VARCHAR(20),#date_of_hours,104),'" + odr[2] + "')";
cmd1.Parameters.Add("#date_of_hours", SqlDbType.DateTime).Value =odr[1];
(this doesn't work because of CONVERT in insert, but is there some similar solution) or
CONVERT(VARCHAR(20),#date_of_hours,104) AS [DD:MM:YYYY]
UPDATE
In other form i read data through combobox. It shows 1.10.2011, 2.10.2011, .... to 16.10.2011.
da_test_data = new SqlDataAdapter("SELECT test_data_id, date_of_hours, number_of_hours FROM test_data WHERE _person_id= '" + person_id_person + "' ORDER BY date_of_hours", conn);
dt_test_data = new DataTable();
da_test_data.Fill(dt_test_data);
cb_datum.DataSource = dt_test_data.DefaultView;
cb_datum.ValueMember = "test_data_id";
cb_datum.DisplayMember = "date_of_hours";
And combobox for projects:
private void cb_datum_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView drvProjekt = cb_datum.SelectedItem as DataRowView;
if (drvProjekt != null)
{
string date1 = drvProjekt["date_of_hours"].ToString();
DateTime date2 = new DateTime();
date2 =Convert.ToDateTime(date1);
//DateTime date = DateTime.ParseExact(date1, "MMddyyyy hh:mm:ss", null);
//DateTime date = DateTime.ParseExact(date1, "dd.MM.yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
//object obj = DateTime.ParseExact(dddd, "MM/dd/yyyy hh:mm", null);
conn = new SqlConnection(connectionString);
conn.Open();
da_projekt = new SqlDataAdapter("SELECT projekt_id, name_of_projekt, date_of_start, date_of_end FROM projekt WHERE date_of_start < '" + date2 + "' AND date_of_end > '" + date2 + "' ", conn);
dt_projekt = new DataTable();
da_projekt.Fill(dt_projekt);
cb_projekt_id.DataSource = dt_projekt.DefaultView;
cb_projekt_id.ValueMember = "projekt_id";
cb_projekt_id.DisplayMember = "name_of_projekt";
conn.Close();
}
}
When i select 13.10.2011 i get error. Date is recognised as MM.dd.yyyy. I tried everything (all in comments and many more). Yust don't find a solution.
As I mentioned in the comment. your date value is stored as Date in SQL. So when you store date in SQL it will remain date only, and when you retrieve it you will get date object directly. In SQL, it might be displayed as MM.dd.yyyy it doesn't matter.
When you will read this data from SQL, you will get DateTime object, on this if you do .ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) you will get in dd.MM.yyyy format. You can use any format on DateTime object, read more about it on MSDN.
Hope this answers your question.
If possible, just replace "." with "/" in the excel file and format the cell as dd/mmm/yyyy
Excel natively keeps dates as days since some date I do not remember as a floating point value. The important thing is that this matches DateTime.ToOADate().
We read dates from excel files as a floating point value and then use DateTime.ToOADate().
You use CONVERT the wrong way. Database-side, you convert a datetime to a string (varchar), and then you have to rely on build-in type conversions to get a datetime again. You should do it the other way around. If in c# you convert the datetime to a string with a specified format and convert it to a datetime with a matching style database-side nothing can go wrong.
When you use CONVERT the date part should match the style you use (in your case 104). Use this in your sql:
CONVERT(DATETIME, #date_of_hours, 104)
and
cmd1.Parameters.Add("#date_of_hours", SqlDbType.NVarChar).Value =
string.Format("{0:dd.MM.yyyy}", odr[1])

Categories

Resources