Convert string to time clarification - c#

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.

Related

How to convert Datetime2 to DateTime in ASP.NET

I need to convert datetime2 (getting data from SQL Server) to datetime (like current time) in ASP.NET.
I use this method but it is not working correctly
Convert.ToDateTime(messageVO.MDateTime).ToString("yyyy-MM-dd h:mm tt")
messageVO.MDateTime is getting from database.
How can I do this? Please help me.
You cannot do a conversion since the implicit DateTime2 mapping to .NET data type is to System.DateTime (see http://msdn.microsoft.com/en-us/library/bb675168.aspx). Without seeing your class definition for the type of messageVO, I would expect MDateTime to be of DateTime data type (especially if you're using entity framework) as part of the mapping standards.

c# SQL Server : DATETIME datatype

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?

Get value of date and store it in MySQL database?

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.

Error in inserting statement when inserting

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

Converting MySQL DATETIME to System.DateTime

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!

Categories

Resources