Date convertion To yyyy-mm-dd - c#

cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = DateTime.Parse(txtStartDate.Text);
The value in txtStartDate.Text is like 31-07-2012
I need to get it as 2012-07-31.
For processing in storedprocedure.
My code is like :
cmd = new SqlCommand("DownloadtoXLSheet", conn);
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = DateTime.Parse(txtStartDate.Text);
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = DateTime.Parse(txtEndDate.Text);
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = DropDownList1.Text.ToString();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt1);
help me out

First off, you don't need the date in a particular format for processing in the stored procedure/database. Once a DateTime has been added as a parameter (of type DateTime), the SQL provider will make sure the SQL server can handle the date.
On the other hand, you might need the date in a particular format for DateTime.Parse to work.
Try:
DateTime.ParseExact(input, "dd-MM-yyyy", CultureInfo.InvariantCulture);
But, maybe you should use DateTime.TryParseExact instead, to avoid exceptions?

Use DateTime.ParseExact method instead of DateTime.Parse.
DateTime result=DateTime.ParseExact("31-07-2012", "dd-MM-yyyy",CultureInfo.InvariantCulture);

try with
DateTime dt = ...;
dt.ToString("yyyy-MM-dd");

In the .ToString() method you can specify a format string
http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd")

Related

How to INSERT date into SQL database date column using dateTimePicker?

I have a birthdate column of type Date in sql database
And in my application I use a dateTimePicker to get the birth date
But when i am trying to insert the date taken from the dateTimePicker:
I get an error :
Incorrect syntax near '12'
And when I try to debug the code I find that the value taken from the dateTimePicker is
Date = {3/21/2015 12:00:00 AM}
The CODE:
//cmd is sql command
cmd.CommandText="INSERT INTO person (birthdate) VALUES("+dateTimePicker.Value.Date+")";
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
What you really should do is use parameters to avoid SQL injection attacks - and it also frees you from string formatting dates - also a good thing!
//cmd is sql command
cmd.CommandText = "INSERT INTO dbo.Person(birthdate) VALUES(#Birthdate);";
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Also, it's a recommend best practice to put your SqlConnection, SqlCommand and SqlDataReader into using(....) { .... } blocks to ensure proper disposal:
string connectionString = ".......";
string query = "INSERT INTO dbo.Person(birthdate) VALUES(#Birthdate);";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
As mentioned before the best practice is to use parameters, but if you really need to use a TSQL statement from source you should use date in the format: yyyymmdd
cmd.CommandText="INSERT INTO person (birthdate) VALUES('"+dateTimePicker.Value.Date.ToString("yyyyMMdd")+"')";
Try including quotes:
cmd.CommandText="INSERT INTO person (birthdate) VALUES('"+dateTimePicker.Value.Date+"')";
I'd recommend using parameters too.
Try this as string format:
cmd.CommandText="INSERT INTO person(birthdate)VALUES('"+dateTimePicker.Value.Date+"')";
dateTimePicker stores values as 1/1/1900 12:00:00 AM so you should use DATETIME if you're trying to store it since DATETIME's format is: YYYY-MM-DD HH:MI:SS.
You can print the dateTimePicker value using
MessageBox.Show(dateTimePicker.Value.ToString());
to see for yourself.

save time into SQL Database

I have a SQL Database with the following structure:
I have 4 MaskedTextBox for:
(Structure)
DateFrom: 0000.00.00
DateFromTime: 00:00:00
DateTo: 0000.00.00
DateToTime: 00:00:00
.
SqlCommand cmd = new SqlCommand("INSERT INTO TABELLE2 (MessageHeadline, MessageText, SpecifyUser, CreateDate, CreateTime, CreateUser, DateFrom, DateFromTime, DateTo, DateToTime) VALUES (#MessageHeadline, #MessageText, #SpecifyUser, #CreateDate, #CreateTime, #CreateUser, #DateFrom, #DateFromTime, #DateTo, #DateToTime)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MessageHeadline", TB_MSGHeadline.Text);
cmd.Parameters.AddWithValue("#MessageText", TB_MSGText.Text);
cmd.Parameters.AddWithValue("#SpecifyUser", TB_SpecifyUser.Text);
cmd.Parameters.AddWithValue("#CreateDate", CreateDate );
cmd.Parameters.AddWithValue("#CreateTime", CreateTime);
cmd.Parameters.AddWithValue("#CreateUser", CreateUser);
cmd.Parameters.AddWithValue("#DateFrom", MTB_DateFrom.Text);
cmd.Parameters.AddWithValue("#DateFromTime", MTB_DateFromTime.Text);
cmd.Parameters.AddWithValue("#DateTo", MTB_DateTo.Text);
cmd.Parameters.AddWithValue("#DateToTime", MTB_DateToTime.Text);
connection.Open();
cmd.ExecuteNonQuery();
TB_MSGHeadline.Clear();
TB_MSGText.Clear();
TB_SpecifyUser.Clear();
And finally I want to save these values from my MasketTextBox into my database to use them later.
I try to change the Structure and try some SQL Date/Time formation but i get the error:
You're passing the DATE parameters in the incorrect format. You need to pass them as a valid DateTime which your MaskedTextBox values do not appear to be.
For example, #DateFrom is a SQL Date data type. You should pass it a valid parameter such as a DateTime:
cmd.Parameters.AddWithValue("#DateFrom", DateTime.Now);
You may need to parse the MaskedTextBox values correct using DateTime.TryParse
DateTime parsedDate;
bool success = DateTime.TryParse(MaskedInputOne.Text, out parsedDate);
if (success) {
cmd.Parameters.AddWithValue("#DateFrom", parsedDate);
}
In this case we are only adding the parameter if the conversion succeeds.

Error in accessing the date in asp.net

DateTime startDate = DateTime.ParseExact(txtstart.Text, "yyyyMMdd", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "yyyyMMdd", null);
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where updateDate between "+
startDate.ToString() + " and "+ endDate.ToString() +" ", con);
It gives error:
String was not recognized as a valid DateTime.When date is entered in
mm/dd/yyyy format
Well yes - you're explicitly specifying that you want to parse it in yyyyMMdd format. I don't see why you'd expect it to work if you've actually specified it in MM/dd/yyyy format. If you want to handle that instead, change your parsing code:
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
However:
If this is parsing user input, you should use DateTime.TryParseExact instead, so you can detect errors in the input in the normal flow instead of using exceptions.
This code is very US-centric; non-US users may well find it confusing. In general you'd either be better off using one of the standard date formats (and the user's culture) or even better, using a date picker control of some form, to avoid the whole text format issue to start with.
Next you're using the values directly in the SQL statement. Don't do that. Always, always, always use parameterized SQL:
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where updateDate between #Start and #End",
con);
adapter.SelectCommand.Parameters.Add("#Start", SqlDbType.Date).Value = startDate;
adapter.SelectCommand.Parameters.Add("#End", SqlDbType.Date).Value = endDate;
(Or create the command first and then pass that to the adapter.)
Using parameterized SQL has three benefits:
It avoids SQL injection attacks
It avoids data conversion issues (which are common with dates)
It keeps your SQL easy to read by separating the code from the data
Access DB Only
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MMddyyyy", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MMddyyyy", null);
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where format( updateDate,'MM/dd/yyyy') between '"+
startDate.ToString("MM/dd/yyyy") + "' and '"+ endDate.Tostring("MM/dd/yyyy") +"' ", con);
Sql Server
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MMddyyyy", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MMddyyyy", null);
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where Convert(varchar(15), updateDate,106) between '"+
startDate.ToString(dd MMM yyyy) + "' and '"+ endDate.Tostring(dd MMM yyyy) +"' ", con);

C# DateTime object + stored procedure

I'm calling a stored procedure from my code using SqlCommand, some of the parameters are of DateTime type, when calling the procedure from Management Studio I use the following format yyyy-MM-dd for example 2011-01-01, and results are returned accordingly.
In my C# code I'm creating the DateTime object like the following:
DateTime dateFrom = new DateTime(2011,01,01);
and when I run the application the dates are being complete ignored and all the data is being returned. After the debugging accordingly I'm noticing that the format of the DateTime object is being: {01/01/2011 00:00:00} so probably this is causing the issue.
The parameters are being added to SqlCommand like this:
cmd.Parameters.AddWithValue("#DateFrom", SqlDbType.DateTime);
Any idea please?
Copying code:
using (SqlConnection conn = new SqlConnection(connectionString))
{
DateTime dateFrom = new DateTime(2011,01,01);
DateTime dateTo = new DateTime(2011, 01, 31);
SqlCommand cmd = new SqlCommand(strStoredProcName, conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DateFrom", SqlDbType.DateTime);
cmd.Parameters.AddWithValue("#DateTo", SqlDbType.DateTime);
cmd.Parameters["#DateFrom"].Value = dateFrom;
cmd.Parameters["#DateTo"].Value = dateTo;
}
There should be no format issue from C# to SQL for date time data type.
There may be 2 things causing this issue:
As far I can remember, you not need to add # for the parameter name
cmd.Parameters.AddWithValue("DateFrom", SqlDbType.DateTime);
The overload of AddWithValue is string parameterName and object value. You have passed SqlDbType.DateTime as the value. Pass your DateTime variable instead.
you have two options either choose Add or AddWithValue with following format:
1) cmd.Parameters.Add("#DateFrom", SqlDbType.DateTime).Value = dateFrom;
2) cmd.Parameters.AddWithValue("#DateFrom", dateFrom);
If the datetime parameter in stored procedure is type of DateTime, you need not to essentially pass the value as datetime. You can pass simple string value like below:
cmd.Parameters.Add("#DateFrom", SqlDbType.DateTime).Value = "23-03-2013";

Date conversion from C# to MySql Format

How to convert C# datetime to MySql Datetime format. I am getting value from text box like 7/27/2011 this format. But i want to convert in this format 2011-7-27. So here i am stuking. Please help me. My objective is to filter the record between two dates and show in a listview control in asp.net.
Here is my code:
DateTime dt1 = Convert.ToDateTime(txtToDate.Text);
DateTime dt2 = Convert.ToDateTime(txtFromDate.Text);
lvAlert.DataSource = facade.GetAlertsByDate(dt1, dt2);
lvAlert.DataBind();
I haven't used MySQL with .NET, but Oracle has similar date conversion issues with .NET. The only way to stay snae with this has been to use parameters for date values, both for input as welll as for WHERE clause comparisons. A parameter created with a MySQL date parameter type, and just giving it a .NET datetime value, should work without needing you to do conversions.
EDITED TO ADD SAMPLE CODE
This code sample shows the basic technique of using parameters for DateTime values, instead of coding conversions to text values and embedding those text values directly in the SQL command text.
public DataTable GetAlertsByDate(DateTime start, DateTime end)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Alerts WHERE EventTime BETWEEN #start AND #end", conn);
DataTable table = new DataTable();
try
{
SqlParameter param;
param = new SqlParameter("#start", SqlDbType.DateTime);
param.Value = start;
cmd.Parameters.Add(param);
param = new SqlParameter("#end", SqlDbType.DateTime);
param.Value = end;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(table);
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
return table;
}
This is SQL Server code, but the technique should be the same for most databases. For Oracle, for example, the only changes would be to use Oracle data access objects, and use ":" in place of "#" in parameter names. The technique for MySQL should also be very similar.
For many databases, shortcuts may exist for creating parameters, such as:
cmd.Parameters.AddWithValue("#start", start);
This works when you know the value is not null, and the correct parameter type can be derived from the C# type of the value. "AddWithValue" is specific to SQL Server; "Add" works also but is obsolete in SQL Server.
Hope this helps.
You can assign format to data time, DateTime.ParseExact() or DateTime.ToString(format), :
the format for 2011-7-27 is yyyy-m-dd
Assuming you are doing this in the database I think you should use date_format to get in the required format
Something like date_format(dateval,'%Y-%c-%d') (Not tested)
I use:
string fieldate = dt1.ToString("yyyy-MM-dd");

Categories