Failed to convert parameter value from string to datetime - c#

myCommand1.Parameters.Add("#I_vBACHNUMB", SqlDbType.Char).Value = GLHdr.BACHNUMB;
myCommand1.Parameters.Add("#I_vREFRENCE", SqlDbType.Char).Value = "ExcelImport";
myCommand1.Parameters.Add("#I_vTRXDATE", SqlDbType.DateTime).Value = GLHdr.TRXDATE;
In last line I have value GLHdr.TRXDATE: "15-02-2017".
I am getting format exception.Let me know where I am doing mistake.

GLHdr.TRXDATE is a string, not a DateTime.
You need to parse it into a DateTime before passing it through:
var dt = DateTime.Parse(GLHdr.TRXDATE);
myCommand1.Parameters.Add("#I_vTRXDATE", SqlDbType.DateTime).Value = dt;
Note that DateTime.Parse can fail, so ParseExact or TryParseExact that also take a format string may be more suitable for you specific circumstances.

Related

String was Not recognised as valid date time C#

I created a web app which is working fine on localhost but when I uploaded the web app, I get an error on my calender
String was not recognized as a valid DateTime.
Line 1291: string strstartdate = "";
Line 1292: strstartdate = txtfrmdate.Text;
Line 1293: DateTime dt = Convert.ToDateTime(strstartdate);
Line 1294: string strfstartdate = dt.ToString(strstartdate);
Line 1295: DateTime dtnew = Convert.ToDateTime(strfstartdate);
It is working fine with the date range of (1/12), but when I choose date between (13/31), I get this error.
This is what is selected (13-09-2016)
My C# page
string strstartdate = "";
strstartdate = txtfrmdate.Text;
DateTime dt = Convert.ToDateTime(strstartdate);
string strfstartdate = dt.ToString(strstartdate);
DateTime dtnew = Convert.ToDateTime(strfstartdate);
SqlCommand cmd = new SqlCommand("csuvdaterange");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
con.Open();
SqlParameter[] param =
{
new SqlParameter("#logintype",com.ToString()),
new SqlParameter("#name",lblempname.Text),
new SqlParameter("#datefrm",DateTime.ParseExact(txtfrmdate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd")),
new SqlParameter("#dateto",DateTime.ParseExact(txttodate.Text,"dd-MM-yyyy",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd"))
};
The CurrentCulture on the web server would appear to be US, and your text isn't in a format where month precedes the day - it's inferring a month of 13, which isn't a valid date.
You should parse the date the same way as your do later in your code:
DateTime.ParseExact(txtfrmdate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture)
Use DateTime.ParseExact instead of Convert.ToDateTime
in order to avoid system from confusion on different regional date format settings I recommend that date format be always mentioned while converting types...

I need only date value part and time value part using ASP.NET C#

I have two parameters one for date and another for time, and i need date value part and time values part.
My two parameters are below.
// For Date parameter
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
bo.Dateused5 = dt;
// For Time parameter
string Fromtiming = ddl_FromHours.SelectedItem.ToString() + ":" + ddl_FromMinutes.SelectedItem.ToString();
DateTime InterviewTime = Convert.ToDateTime(Fromtiming);//StartTime
bo.Dateused4 = InterviewTime;//InterviewTime
so i need to send mail to the candidate to only date part, should not contain time and time part, should not contain date.
are you looking for this:
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
string mailDate = dt.ToString("dd-MMM-yyyy");// will give 01-jan-1999
string date = dt.ToString("dd-MM-yyyy"); // will give 01-01-1999
You can also try using String.Format()
string mailDate = String.Format("{0:dd-MM-yyyy}", dt); // will give 01-01-1999
You can use ToShortDateString():
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
var date = dt.ToShortDateString();
Note that it uses date format attached to the current thread's culture info.
You would need to use strings rather than dates, so change the type of your variables to string so that
bo.Dateused5 = dt.ToString("dd-MMM-yyyy")
would set Dateused5 to a string of the date component, then
bo.Dateused4 = InterviewTime.ToString("HH:MM");
would set Dateused4 to the time component.
Couldn't test your code but I am very sure there are Functions "DateValue" and "TimeValue" you can make use of.
Something like,
Format(DateValue(any datetime), "dd-MM-yyyy")
gives you Only Date in the specified format. Similar way for TimeValue

Which SQL Date format

Which date format does T-SQL use? Does it rely on the system date? How can I be sure that my parameters are passed on correctly regardless of system date format. This question comes because of error:
Error converting data type nvarchar to datetime.
The SQL script in part:
CREATE PROCEDURE [dbo].[sz_pipeline04_pipelUpdte_inventory]
-- Add the parameters for the stored procedure here
#myFixDte datetime,
#doInsert bit
AS
BEGIN
The calling c# code:
public static DataTable GridInventory(string strdProcedureName, DateTime fixDate, bool execInsertYN)
{
DataTable dtbl_inventory = null;
try
{
dtbl_inventory = new DataTable();
using (var conn = new SqlConnection(cls_connRegistry.GetConnStrFull()))
using (var command = new SqlCommand(strdProcedureName, conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
command.Parameters.Add("#doInsert", SqlDbType.Bit).Value = execInsertYN;
conn.Open();
SqlDataReader dr = command.ExecuteReader();
dtbl_inventory.Load(dr);
conn.Close();
}
}
catch (Exception datawalile)
{ dtbl_inventory = null; }
return dtbl_inventory;
}
edited question.
The code you've now posted looks correct - except for one thing:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
As I've said in the comments, issues only come up around formatting when you convert to strings. So just do:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = fixDate;
DateTimes (C#) and datetime (T-SQL) don't have a format. You get formatting issues when you convert them into strings. In their native representation, they're usually just a count of a number of events (ticks, milliseconds, etc) since some fixed point in the past. ADO.Net knows how to convert a DateTime into a SQL Server datetime.
If you have remaining conversion issues, it's in code you've not yet shown. But it will, again, be because you're converting away from the correct data type (datetime) and using strings.
This is not valid DATETIME format DD-MM-YYYY.
You can use CONVERT It in following:
DECLARE #myFixDte DATETIME
SET #myFixDte = CONVERT(DATE, N'30-12-2012', 104)
SELECT #myFixDte
Or you can SET It without converting in other format like YYYY-MM-DD
Try this:
#myFixDte = convert(datetime, '30-12-2012', 105)
And check the link provided by #N.Molderf
SQL Server recognizes one format always in same way, regardless which culture it using, and that format is YYYYMMDD.
So you can always use your dates in format 20120202 or 20151225, and SQL Server will parse that parameter using same mask.
Why you didnt tell as above c# datetime, here is a simple example for you how to solve this problem in your case it will be something like this
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("dd-MM-yyyy HH:mm:ss");
or this one
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
second one is a default

how to convert datetime format

hi i am giving a textbox to user and ajax calender extender to select date in dd/mm/yyyy format after that i am using following function to convert it to mm/dd/yyyy format for inserting in to sql server database but it not work well in one page i got error datetime conversion error and in other i have to enter yyyy/mm/dd format to insert data into database. my code works fine in localhost but in server these errors are coming . my function is
protected string getDate_MDY(string inDate)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");
DateTime dtProjectStartDate = Convert.ToDateTime(inDate);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
return (Convert.ToDateTime(dtProjectStartDate).ToString("MM/dd/yyyy"));
}
and for inserting i used it like getDate_MDY(txtcreatedate.text);
i just want to insert my correct date in to database by taking dd/mm/yyyy format from text box. . please show me right way to modify it...thanks
Use DateTime.Parse or DateTime.ParseExact instead of changing the current thread culture. Both of these methods have overloads that take a culture to use when parsing the string.
For example:
protected string getDate_MDY(string inDate)
{
DateTime date = DateTime.Parse(inDate, new CultureInfo("en-GB"));
return date.ToString("MM/dd/yyyy", new CultureInfo("en-US"));
}
This isn't the most efficient way to do this (you'd probably want to cache the CultureInfo instances for starters) but it will do what you asked for (ie. convert a date/time string from one culture to another).
However, as someone pointed out in the comments, you shouldn't be passing date strings to a SQL command. Instead, they should be defined as date/time parameters in the SQL command:
using (var connection = new SqlConnection("<your connection string>"))
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO (sometable) VALUES (#somedatecolumn)";
command.CommandType = CommandType.Text;
var parameter = new SqlParameter("#somedatecolumn", SqlDbType.SmallDateTime);
parameter.Value = <your date/time value>; // a DateTime value, not a string
command.Parameters.Add(parameter);
command.ExecuteNonQuery();
}
It seems that you should only add DateTimeFormatInfo to your Convert.ToDateTime(inDate) --> Convert.ToDateTime(inDate, DateTimeFormatInfo)
System.Globalization.DateTimeFormatInfo dtfi = null;
DateTime dtProjectStartDate = new DateTime(2008, 4, 10); //year, month, day
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
dtfi = ci.DateTimeFormat;
txtBox.Text = dtProjectStartDate.ToString("d", dtfi); // 10/4/2008
System.Globalization.CultureInfo ciForSQL = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
System.Globalization.DateTimeFormatInfo dtfiForSQL = ciForSQL.DateTimeFormat;
DateTime dtForSQL = Convert.ToDateTime(txtBox.Text, dtfiForSQL);
txtBoxForSQL.Text = dtForSQL.ToString("d", dtfiForSQL); // 10/4/2008
Use..DateTime.ParseExact
DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm:ss",
CultureInfo.InvariantCulture
).ToString("MM/dd/yyyy");

Cannot implicitly convert type 'string' to 'System.DateTime'

I am trying to convert from string to DataTime but an an error occurs.
I am using VS 2003, .NET Framework 1.1
DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);
Cannot implicitly convert type 'string' to 'System.DateTime'
Can any one help me me with the syntax how to solve the error.
string input = "21-12-2010"; // dd-MM-yyyy
DateTime d;
if (DateTime.TryParseExact(input, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out d))
{
// use d
}
I guess that you have made a typo - change Convert.ToString(s2) to Convert.ToDateTime(s2).
You should be using DateTime.Parse, or DateTime.ParseExact.
DateTime dt= DateTime.Parse("11/23/2010");
string s2=dt.ToString("dd-MM-yyyy");
DateTime dtnew = DateTime.Parse(s2);
Both have TryXXX variants that require passing in an out parameter, but will not throw an exception if the parse fails:
DateTime dt;
if(td = DateTime.TryParse("11/23/2010", out td))
{
string s2=dt.ToString("dd-MM-yyyy");
DateTime dtnew = DateTime.Parse(s2);
}
DateTime dtnew = Convert.ToString(s2);
problem is that your converting string s2 to string again and store it in DateTime variable
Try this:
DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToDateTime(s2);
Try DateTime.Parse(...) or DateTime.ParseExact(...) if you need to specify the format.
DateTime.Parse("01/01 2010");
or use
DateTime.TryParse
if you aren't sure it converts every time, ie. not always a date, but sometimes blank.
This worked for me.
DateTimeConverter c = new DateTimeConverter();
DateTime dt = (DateTime)c.ConvertFromString("2012-05-10");
OR
DateTime dt2 = (DateTime)TypeDescriptor.GetConverter(dt).ConvertFrom("2012-05-21");
You need to change double quotes ("") to single quotes ('')

Categories