String was not recognized as a valid DateTime in C# asp.net - asp.net

I want to import date value from excel cell. cell value having "10 October 2013" format. I want to convert it to datetime data type. My code getting error "string was not recognized as a valid datetime"
//code
OleDbCommand olecmd = new OleDbCommand("select * from [Sheet1$]", olecon);
OleDbDataReader olerdr = olecmd.ExecuteReader();
while (olerdr.Read())
{
deldate = olerdr.GetValue(13).ToString();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["irisdb"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("procdamandrugs", con);
cmd.CommandType = CommandType.StoredProcedure;
DateTime dt = DateTime.ParseExact(deldate, "MM/dd/yyyy", CultureInfo.InvariantCulture);//getting error in this line
SqlParameter par9 = new SqlParameter();
par9.ParameterName = "#deleffdate";
par9.SqlDbType = SqlDbType.DateTime;
par9.Value = dt;
cmd.Parameters.Add(par9);
cmd.ExecuteNonQuery();
}
}
Do any one help me to solve this issue.

cell value having "10 October 2013" format.
You are giving wrong format in ParseExact that does not match with the date string you are passing. You need different format than you gave. For day you need dd, for month you need MMMM and for year you need yyyy and you have to give spaces as separator.
It is worth the article Custom Date and Time Format Strings on MSDN for using the string formats for date conversion.
DateTime dt = DateTime.ParseExact(deldate, "dd MMMM yyyy", CultureInfo.InvariantCulture);

I recommend the utilizing the DateTime.TryParse method before constructing your SQL objects. Ensure you have quality input before having a conversation with your database.
http://msdn.microsoft.com/en-us/library/ch92fbc1%28v=vs.110%29.aspx
Below is a sample from my own code for an asp.net application
// Validation
DateTime dtOut_StartDate;
if (!DateTime.TryParse(txtStartDate.Text, out dtOut_StartDate))
{
Message = "Start date is not a valid format.";
txtStartDate.CssClass = ErrorCssClass.TextBox;
txtStartDate.Focus();
return false;
}

Select Date Time setting from Right lower bottom & Change the format from here......

Related

How do i save time from dropdownlist to database?

my dropdown is like this
here iam storing selected value of dropdown into variable of type 'TimeSpan' and saving in database. But it gives exception: 'String was not recognized as a valid TimeSpan.' my database fieldtype is also Time(7)
DateTime start_time = DateTime.ParseExact(starttime.SelectedItem.Text, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan stt = start_time.TimeOfDay;
SqlCommand com = new SqlCommand("INSERT INTO IvrDatas starttime values #starttime",conn);
com.Parameters.AddWithValue("#starttime", stt)
Please help me out in this matter.
"11:00 AM" cannot be parsed with the TimeSpan.Parse function. You could use the ParseExact function as follows:
DateTime.ParseExact(starttime.SelectedItem.Text, "hh:mm tt", CultureInfo.InvariantCulture);
You can extract the time from the Parsed datetime with the ".TimeOfDay" function. That will give you the proper value and type

Unable to correctly save DateTime into SQL Server 2012

I have 2 controls taking input of the date and time separately. Namely txtDateOutGv for the date and txtNewActionTimeOutGv for the time in hh:mm tt format from a time picker control.
I have tried many ways to insert into my SQL Server 2012 database and have never been able to successfully save the time. The saved time is always 2014-10-04 00:00:00
What is the approach for this? I have tried using stored procedures and it didn't work either.
Dim strActionTimeOut As String = DirectCast(gvActions.FooterRow.FindControl("txtDateOutGv"), TextBox).Text + " " + Convert.ToDateTime(Request.Form(DirectCast(gvActions.FooterRow.FindControl("txtNewActionTimeOutGv"), TextBox).UniqueID)).ToString("HH:mm:ss")
Dim actionTimeOut As DateTime
actionTimeOut = DateTime.ParseExact(strActionTimeOut, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
actionTimeOut = Format(Convert.ToDateTime(strActionTimeOut), "yyyy-MM-dd HH:mm:ss")
insertAction As String = "INSERT INTO Actions([TimeOut]) VALUES ("+ CONVERT(date, CONVERT(DATETIME, '" + actionTimeOut + "', 0), 120)" + ")"
The time format should be as converted in the SQL Server too.. Not sure if that is the issue.
Yes, your code does exactly that:
CONVERT(date, CONVERT(DATETIME, '" + actionTimeOut
You convert the input value to a datetime (unnecessary) and then to a date. The last convert will loose all time info, as expected.
Use a datetime parameter:
SqlCommand cmd = new SqlCommand("INSERT INTO Actions([TimeOut]) VALUES (#actionTimeOut);");
cmd.Parameters.AddWithValue("#actionTimeOut", actionTimeOut);
cmd.Execute(...);
Seconds will always 00 when using SmallDateTime; seconds supplied will be rounded.
Also, don't use 'HH' for the 'hour' time format, use 'hh'. This will be the same regardless of whether you're using stored procs, direct SQL or a data layer.
Can you try this as a test. Sorry I wrote it in C# but you get the idea; it's just a test to insert a single hard-coded value using the format as shown below. This works for me here - if it doesn't work for you, it's almost certainly the format of your date. Again, note I am not supplying seconds as a parameter because SmallDateTime does not store it: -
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Actions([TimeOut]) VALUES ('2014-01-01 17:30')", conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();

string is not supported in calendar System.Globalization.GregorianCalendar

i am having problem with my retrieving of date after the date fall after 12. for example : if i click from the calander extender: 2/7/2013 to 19/july/2013 , is will throw it me with this error : The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
this is my code.
var format = "MM/dd/yyyy";
DateTime one = DateTime.ParseExact(startdate, format, CultureInfo.InvariantCulture);
DateTime two = DateTime.ParseExact(enddate, format, CultureInfo.InvariantCulture);
if (two >= one)
{
SqlConnection conn = new SqlConnection("Data Source=""catalog="";Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT Name,CLass, NRIC, StallNo, AmountSpent ,TimeDate=convert(nvarchar,timedate,103) FROM StudentTransactions WHERE TimeDate BETWEEN '" + one + "' AND '" + two + "'", conn);
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.DataBind();
conn.Close();
}
try this
select CONVERT(varchar,<datecol>,103) --- and will return as dd/mm/yyyy
where convert(date,<datecol>) between '' and ''
If you want to alter the format of a column of a GridView from CodeBehind Add a RowDataBound to your grid view.
Then in the GridView_RowDataBound(object sender, GridViewRowEventArgs e) method, you'll be able to access e which will provide you with access to the individual cells of that row where you can specify a format.
Reference
Reference2
Make sure first that the date part of your TimeDate column is in your desired format, i.e., "dd/mm/yyyy".
var format = "dd/mm/yyyy";
DateTime one = DateTime.ParseExact(startdate, format, CultureInfo.InvariantCulture);
DateTime two = DateTime.ParseExact(enddate, format, CultureInfo.InvariantCulture);
EDIT:
To format the output, you can do ff:
Assuming you have a Boundfield on your TimeDate on your GridView1:
<asp:BoundField DataField="TimeDate" HeaderText="TimeDate" DataFormatString="{0:dd/MM/yyyy}" />
You can also use DataFormatString="{0:d}" to output the date in the short date format of your current culture.

Have kept format of ajaxcalendar control as "dd/mm/yyyy" and want to save in database as mm/dd/yyyy

I m using ajax calendar control to a textbox, have set its format as "dd/mm/yyyy" .
Bapur.Date = txtdate.Text;
in data access layer
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = bapur.Date;
on saving, like above ( where Date is a string Bapur is object of businesslayer class)
in the database where datatable in database has date as datetime format.
m getting an error : cant convert string to datetime i dint get error when format was "mm/dd/yyyy" .
Basically, I want users to view date in dd/mm/yyyy but on saving i want it in
mm/dd/yyyy
Have tried a lot but not working.
here is my answer ---- https://stackoverflow.com/a/11720162/1445836 -----
You can use:
DateTime.ParseExact("yourDate","formatinWhichYouWant",culture of current string);
ex:
DateTime dt =DateTime.ParseExact("yourDate","formatinWhichYouWant",culture of current string);
string myDate = bapur.Text.Split("/");
string dateString = myDate[1] + "/" + myDate[0] + "/" + myDate[2];
got my answer
string old = txtdate.Text;
string newDate = DateTime.ParseExact(old, "dd/MM/yyyy", null).ToString("MM/dd/yyyy");
Bapur.Date = newDate.ToString();

Converting Date From TextBox To Date In ASP.Net

I want to get the difference of date from Two TextBox say to and from dates..
My Code is here
Dim ts As TimeSpan
ts = CDate(txtTo.Text) - CDate(txtFrom.Text)
txtDays.Text = ts.Days() + 1
but this code is throwing an error like this
Conversion from string "16/11/2011" to type 'Date' is not valid.
In general, try to avoid using old VB functions like CDate. In this case, you should use the Parse method:
Dim ts As TimeSpan
ts = DateTime.Parse(txtTo.Text) - DateTime.Parse(txtFrom.Text)
Or, if you know the date format in advance:
Dim fmt As String = "dd/MM/yyyy"
Dim ts As TimeSpan
ts = DateTime.ParseExact(txtTo.Text, fmt, Nothing) - DateTime.ParseExact(txtFrom.Text, fmt, Nothing)
Try using ParseExact like:
Dim s As String = txtFrom.Text.trim
Dim pattern As String = "dd/MM/yyyy"
Dim parsedDate As Date = Date.ParseExact(s, pattern, Nothing)
As that way you can specify the format of the string that is used.
More direct to your example:
Dim pattern As String = "dd/MM/yyyy"
ts = Date.ParseExact(txtTo.Text, pattern, Nothing) - Date.ParseExact(txtFrom.Text, pattern, Nothing)
You can directly cast a string to DateTime. You need to use the DateTime.Parse function to parse a string to a DateTime.
The syntax can be found here.
Use overloaded version of the function:
DateTime value = DateTime.Parse(txtFrom.Text, new CultureInfo("gu-IN", false));
where "gu-IN" is for Gujarati (India)

Resources