I am having an application that shows date and time in datagridview after exporting data from database to dataset.
Details : I have a column called Date that contains date and time in datetime2 format and when showing date, seconds don't show up.
con = new SqlConnection();
con.ConnectionString = my_connection_string;
con.Open();
adap = new SqlDataAdapter("SELECT Date,Object,ASDU,IOA,Alarm from Alarms_List",my_connection_string);
ds = new System.Data.DataSet();
adap.Fill(ds, "Alarms_List");
dataGridView1.DataSource = ds.Tables[0];
Example : Date table contains 15/07/2016 10:03:13
It's shown as : 15/07/2016 10:03
I have also tried CAST(Date AS DATETIME2) in the select statement but none of them works
You must set the "Format", sample like this :
dataGridView1.Columns[0].DefaultCellStyle.Format = "dd.MM.yyyy HH:mm:ss";
use :
select CONVERT(varchar(19), dateColumnName, 120) from tableName;
update:
You may also use the FORMAT function from SQL Server 2012 onwards as below:
select FORMAT(dateColumnName, date-format) from tableName;
ex
select FORMAT(GETDATE(), "dd/MM/yyyy hh:mm:ss");
Related
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
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'
I develop an application in .Net C# that retrieves and insert data in a MySQL database.
To establish the connection I use MySqlConnection...
Inside my database, there is several tables each containing multiple date columns in format (yyyy-mm-dd hh: mm: ss)
My problem is that when I get columns by SQL request, my dates are in format (dd-mm-yyyy hh:mm:ss).
I could use the DateFormat() to format the columns, but there are a lot of columns date, and the request can change.
I would like to know if there is a way to impose a date format in the string MyConnection or something like that.
My string is:
string MyConnection = "datasource=192.168.0.1;port=3306;username=" + this.textBoxLogin.Text.ToString().Trim() +
";password=" + this.textBoxPassword.Text.ToString().Trim() + ";AllowZeroDateTime=True;TreatTinyAsBoolean=False;";
Queries + Getting Data + insertion in .xls file:
MySqlConnection conn = new MySqlConnection(MyConnection);
MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
conn.Open();
dataAdapter.SelectCommand = new MySqlCommand("Select * From table;", conn);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
////get data
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
////insert in .xls File
DataSet dataSet = new DataSet();
dataSet.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dataSet.Tables.Add(dataTable);
CreateWorkbook("test\\Export.xls", dataSet);
Date format in Database: 2015/02/25 13:28:25
Date format in my .xls file: 25/02/2015 13:28:25
If the database stores the data in a date, datetime or timestamp data type, .NET will put that in a DateTime struct. This is perfectly fine since this is just the structure of the data, not the visual representation of it.
If you want to change the default date format of your program (which fixes it once for all for all dates), you can set the CurrentCulture to a culture that you require:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
If you just need to set the date format, you can set Thread.CurrentThread.CurrentCulture.DateTimeFormat and Thread.CurrentThread.CurrentUICulture.DateTimeFormat.
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..
I have 2 datetimepickers. In my select query i want to fetch records between these dates. datatype for date in database in varchar(MAX). For datetimepicker i have set custom format as dd-MM-yyyy. Here is my sql query
SqlDataAdapter da = new SqlDataAdapter("Select custname From tb_customer WHERE date >= '"+dtp_fromdate.Text+"' AND date <= '"+dtp_todate.Text+"'", con);
For eg: if my start date is 9-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and 11-06-2012
Incase if my start date is 10-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and not 11-06-2012
Please help
Use Convert or Cast T-SQL to convert VARCHAR value to Date or DateTime and also learn/use parameters instead of hard-coded SQL string.
The problem lies in lack of use of parameters. Using parameters will avoid any minsunderstanding between you and yuor database backend
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlDataAdapter da = new SqlDataAdapter();
string query = "Select custname From tb_customer WHERE date >= #from AND date <= #to"
da.SelectCommand = new SqlCommand(queryString, con);
da.SelectCommand.AddWithValue("#from" , dtp_fromdate.Value);
da.SelectCommand.AddWithValue("#to" , dtp_to.Value);
da.Fill(ds);
return ds;
}