I am using a MySQL database with DbLinq, but there is an exception being thrown:
"Cannot convert mysql datetime to
system.datetime"
How can I resolve this issue?
Check for any zero date means date like '0000-00-00' in database;
this could be the cause of error.
Either cast the MySqlDateTime as a DateTime or use mySqlDateTime.GetDateTime().
Well, if you have a result set containing MySql DateTime values, you could use the ConvertAll method along with a delegate using DateTime.Parse to create a collection of System.DateTime values.
Here's an example, where "results" is the result of your dblinq query containing MySQL datetime values:
List<DateTime> dateTimes = results.ConvertAll(delegate(string time){
return DateTime.Parse(time);
});
Is this what you're looking for?
I was moving a column in my gridview from asp:BoundField to asp:TemplateField so had to display a date from a MySQL database explicitly. I found, through reflection, that the collection typed the date fields as MySqlDateTime and not system.DateTime.
I added the import MySql.Data.Types statement to the code behind and the following Eval statement within a label in the context of a gridview.
Text='<%# CType(Eval("Submitted_Date"), MySql.Data.Types.MySqlDateTime).ToString%>'
output format: 02/23/2011
Hope that helps!
Related
I am writing a unit test which stores an object with a DateTime parameter into a DATETIME2 SQL Server database column. I then create a temporary DateTime object called new_date_time and set that value to DateTime.Now.
The new_date_time value is then used to update the previous value and the SQL query to do this completes successfully.
When re-reading the object back from the database I receive the correct datetime values for days/hours/minutes but the .Ticks value is different from the new_date_time variables .Ticks property. The value returned from the read call returns the last 4 digits of the .Ticks property as zeros.
Why is this rounding occurring making my Assert.AreEqual fail?? :)
Thanks
I guess you are using Parameters.AddWithValue when writing the date to Sql Server. From MSDN the inferred type of a CLR DateTime is SqlDbType.DateTime and not SqlDbType.DateTime2 so the precision is being lost when writing your date to the database.
Explicitly setting the type to datetime2 will solve the issue. For example:
command.Parameters.AddWithValue("#now", DateTime.Now).SqlDbType =
SqlDbType.DateTime2;
Edit
#marc_s makes a good point with his comment:
You should read (and embrace!) Can we stop using AddWithValue() already?
To avoid these kind of issues from biting you, you could get into the habit of using the Add method on the parameters collection which takes the SqlDbType in some overloads and then set the Value property on that rather than using the AddWithValue method:
command.Parameters.Add("#now", SqlDbType.DateTime2).Value = DateTime.Now;
Maybe your database field is not storing your entire DateTime.Now value, because it's not precise enough. Why don't you simply compare your dates after you've formatted them as you like?
eg: (untested):
var databaseDate = d1.ToString("MM/dd/yyyy HH:mm:ss.fff");
var tempDate = d2.ToString("MM/dd/yyyy HH:mm:ss.fff");
Assert.AreEqual(databaseDate, tempDate);
I tested: using Linq To Entities My DateTime.Now is correctly saved to my datetime2(7) and equality test return True.
Are you sure you're passing your correct datetime value to the database? without truncating it?
I have this 21/10/1999 value manually inserted into the SQL database and when I retrieve it like this:
txtDOB.Text = readPatient["pDOB"].ToString();
It displays everything along with the time 12:00:00 AM. My data type for my date column is date, not datetime. So why is it displays the time as well?
((DateTime)readPatient["pDOB"]).ToString("d");
For a list of supported formats see: http://msdn.microsoft.com/es-es/library/zdtaw1bw(v=vs.110).aspx
You may try
txtDOB.Text = Convert.ToDateTime(readPatient["pDOB"]).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Edit: Thanks to comments saw that forgot to cast to datetime
It looks like you got your answer on how to properly format the value to a string without the time portion. But, no one has answered your other question:
So why is it displays the time as well?
This is because of mappings between SQL and .NET. In .NET a SQL "date" is stored in a DateTime object which does have time as well. To see all mappings between SQL and .NET see this: SQL Server Data Type Mappings
you can try this
txtDOB.Text=Convert.toDateTime(readPatient["pDOB"]).ToString("d/MM/yyyy");
You can use the string format parameter of the ToString to achieve any format you like,
like this:
TextBox1.Text =Convert.toDateTime(readPatient["pDOB"]).ToString("d/MM/yyyy");
Click on the datetimepicker then go to properties. There you can format your datetimepicker. Change format to custom (there few selection there) then set custom (provided in the properties menu) table with yy-MM-dd,an
DateTime dt = Convert.ToDateTime(sqdr["invdate"].ToString());
dt.Date; //To get the date only
I've got the error:
INPUT STRING WAS NOT IN A CORRECT FORMAT
when running the code below.
So what do you think here is the error? How will I format the date in the DateTimePicker to store properly in MySQL database?
Here is my code (I included only the relevant code which I think is the error):
cmd.Parameters.AddWithValue("#Rdate", _order.dateTimePicker_Requested.Value.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#Ndate", _order.dateTimePicker_Needed.Value.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#CodeDate", Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd hh:mm:ss"));
Unless your MySQL columns are strings (which they shouldn't be), you should be passing actual dates as parameters.
Don't call .ToString().
You should set :
string.Format("{0:yyyy-MM-dd}", your_date);
Hope this helps!
If your variable represents datetime value then its no need to convert it to string it automatically mapped with MySQL column type and if it still not work then reply.
I will post with some code that will convert datetime to proper so that it would mapped with column.
Thank you.
I am working on c# project and using winform.
Here the problem is the query was working previously but now it is not working
Here the todaydate is a datetimePicker which is set to short date format
and my datatype of column is smalldatetime the error i am getting is
The conversion of a nvarchar data type to a
smalldatetime data type resulted in an out-of-range value.
The statement has been terminated.
if i have two date time picker one for date and second for time then how can i insert? please can you guide me
AddWithValue determines the datatype of the parameter from the value you pass.
In your case you are passing a string and thus the parameter is passed to the database as a string not as a datetime expected by the database
you should change that line
cmd.Parameters.AddWithValue("#today", todaydate.Value);
You're currently passing in the text value, which means something else is having to then parse it as a date. Don't do that. Given that you've got a DateTimePicker, you should just use the DateTime value it provides:
cmd.Parameters.AddWithValue("#today", todaydate.Value);
... or create the parameter first with a specific type (SqlDbType.SmallDateTime), then set the value using todaydate.Value. The important point is to avoid the string conversion.
Wherever possible, you should avoid converting values into text. Keep them in their "natural" form (e.g. DateTime in this case) for as much of the time as possible: on input, parse into the natural form, and if you can avoid ever converting to a string, do so!
I think your time7 column in database is smalldatetime and you tried to assign it a string. I don't suggest it.
Try with Add() method like this;
command.Parameters.Add("#today", SqlDbType.SmallDatetime);
command.Parameters["#today"].Value = todaydate.Value;
or you can use AddWithValue() as also like this;
cmd.Parameters.AddWithValue("#today", todaydate.Value);
I have a string like this: 16:00 and I want it to be saved in my SQL Server database in a column which has a data type of time(7)...
Of course, before I save it in there, I need to convert my string in a time data type.
Upon using Convert.ToDateTime, I get an error:
Cannot implicitly convert type 'System.DateTime' to 'System.TimeSpan'
That is because I am saving Convert.ToDateTime(myString) into a property of an entity from my database which has time(7) data type...
Are there other ways of converting my string into a format which is compatible with the time(7) datatype in SQL Server?
The managed type that corresponds to the SQL time data type is TimeSpan (or TimeSpan? when nullable), not DateTime – refer to Mapping CLR Parameter Data for the list of type conversions.
You can use TimeSpan.Parse(myString) to convert your string.
Use SQL Server's Convert function
convert(DateTime, '20:10:00:000', 114);
See CAST & CONVERT
You can also use it like this
Convert.ToDateTime(myString).TimeOfDay();
This will return the time . And you can pass this value to Sql command parameter.
TimeOfDay returns TimeSpan object.
TimeSpan tp = Convert.ToDateTime(myString).TimeOfDay();
Instead of Convert.ToDateTime use DateTime.TryParseExact(yourTimeString, "HH:mm",<other parameters>, out dateTime);
Other parameters are missing. Please look into the DateTime.TryParseExact documentation. But basically it converts your string to dateTime from the format you are specified.