String was Not recognised as valid date time C# - 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...

Related

How to extract time from Datetime

Im trying to extract time from Datetime and then converting it into int to add 10 to it and then convert it into Datetime and store in the database. But I keep getting following error:
"String was not recognized as a valid DateTime."
Following is the code:
MySqlConnection conn = new MySqlConnection(connection);
String query = "Select timings from topogen.token_gen order by timings desc limit 0,1;";
MySqlCommand cmd = new MySqlCommand(query, conn);
String location = "";
conn.Open();
MySqlDataReader r = cmd.ExecuteReader();
string timings="";
while( r.Read()){
timings = r["timings"].ToString();}
DateTime time = DateTime.Parse(timings); //error appears here
timings = time.ToString("HH:mm:ss");
time = DateTime.Parse(timings);
long t = time.Ticks;
t += 10;
timings = t.ToString("HH:mm:ss");
TextBox1.Text = timings;
time = DateTime.ParseExact(timings, "HH:mm:ss", null);
this.Location = location;
conn.Close();
Looks like your r["timings"].ToString() generates a string representation that your CurrentCulture does not have a standard date and time format. That's why your DateTime.Parse throws FormatException.
Change your timings column type to datetime type even it doesn't.
Use GetDateTime() method of MySqlDataReader to get it's value as DateTime
MySqlDataReader r = cmd.ExecuteReader();
if(r.Read())
{
DateTime timings = r.GetDateTime(0);
}
Let's look the rest of your code. They have also some mistakes.
long t = time.Ticks;
With this, you will get Ticks of your DateTime which looks like for example; 2,193,385,800,000,000.
t += 10;
With this, you will get 2,193,385,800,000,010 which is okey for now because it is a long and this is just an addition.
timings = t.ToString("HH:mm:ss");
Here a mistake. You try to get string representation of your long which uses NumberFormatInfo of your CurrentCulture. It doesn't even use DateTimeFormatInfo. That's your your timings will be HH:mm:ss as a string. And you will try to parse it as DateTime.ParseExact(timings, "HH:mm:ss", null) which is equal to DateTime.ParseExact("HH:mm:ss", "HH:mm:ss", null). As you can see, this parsing operation will fail.
Consider to changing your logic.

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

Error while converting textbox content to DateTime format in C# ASP.net

Hi i am developing an application, in that i required to store date in sql server 2005 database which is retrieved from a textbox in front end. In front end, user is allowed to pick a date from JQuery UI DatePicker plugin.
Error I am getting is as follows:
String was not recognized as a valid DateTime.
Code i have is:
db.eventDate = DateTime.Parse(txtDate.Text, new CultureInfo("en-US").DateTimeFormat);
Try this code
string yourDate = txtDate.Text;
string formattedDate = yourDate.ToString("dd-MM-yyyy");
DateTime dt = DateTime.ParseExact(formattedDate , "dd-MM-yyyy", CultureInfo.InvariantCulture);
You should either use DateTime.TryParse(expression) or wrap your call to DateTime.Parse in a try/catch block. Just out of interest, can you post some example dates you're converting ? They are in US format, right ?
you better use DateTime.ParseExact with the correct date time format you set to date time picker
for example if the format is "MM/dd/yyyy" you can do as below
db.eventDate = DateTime.ParseExact(txtDate.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Try this..Working fine for me..
Convert.ToDateTime(txtDate.Text,System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);
or
Convert.ToDateTime(txtDate.Text);
Hope following code helps you.
Dim dt As New DateTime
Dim txtDateFromUser As String = "04/09/2014"
If DateTime.TryParse(txtDateFromUser, dt) = True Then
Dim connStr As String
connStr = System.Configuration.ConfigurationManager.ConnectionStrings("youConnectionStringName").ConnectionString
'Insert into database
Dim sqlconn As New SqlConnection
sqlconn.ConnectionString = connStr
Dim sqlcmd As New SqlCommand("insert into tblDateTime (dtTestDate) values ('" + dt.ToString() + "')")
sqlconn.Open()
sqlcmd.Connection = sqlconn
sqlcmd.ExecuteNonQuery()
End If
Here is the test table I've used:
create table tblDateTime (dtTestDate datetime)
i simply changed the date format of JQuery UI DatePicker in my code. Before it was in UK format so i was getting error while saving data to database. But once i change it to US format it working fine.
I thanks for everyone who reviewed my question and suggested me the answers.

unable to convert string to date in asp.net correctly

I unable to convert string to date, my string like 17/12/2012
Code written for this is shown below
public string Date_Convert(string dt1)
{
string strdate = string.Empty;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
DateTime dt = Convert.ToDateTime(dt1);
strdate = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
return strdate;
}
It is working fine in my local system. And not working in my server(which is located at Australia)of course I tried with different culture settings in the above code,
I'm using this date string in sql query in where condition.
please help me, It killed my one day time, and thanks in advance.
Instead of switching the culture, why don't you do something like this:
public string Date_Convert(string dt1)
{
DateTime dt = DateTime.ParseExact(dt1, "dd/MM/yyyy", new CultureInfo("en-GB"));
return dt.ToString("d", new CultureInfo("en-US"));
}
Also: If you use the value in an SQL query (and provided that your query works on a DATETIME field, not NVARCHAR), you should also consider using a parameterized query to pass the DateTime value to the database to avoid SQL injection.
For example:
DateTime value = DateTime.Parse(dt1, new CultureInfo("en-GB"));
using (SqlCommand cmd = new SqlCommand("SELECT ... FROM ... WHERE Date = #date", connection))
{
cmd.Parameters.AddWithValue("#date", value);
...
}
Try DateTime.ParseExact() it receives as parameter the pattern so for your case it would be "dd/MM/yyyy"
The format of the DataTime will depend on the current culture of your application. Inorder to have a specific format throught your application you can set the tag in the web.config file under section. In such case you need not write code to convert the datatime to proper format. By default all the dates will be set to the format specified.
http://forums.asp.net/t/1109183.aspx/1
More Info

Failed to convert parameter value from string to datetime

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.

Categories