//I have this code and I want to insert only the date in the database without //the time, but this will always store value like this: 2019-10-19 00:00:00.000.
SqlCommand cmd2 = conn.CreateCommand();
cmd2.CommandType = CommandType.Text;
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
string time1 = TextBox_DepartureTime.Text + " " + DropDownListAMPM.SelectedValue;
string time2 = TextBox_ArrivalTime.Text + " " + DropDownList_AMPM2.SelectedValue;
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
if (date <= DateTime.Now.Date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Departure Date Cannot be in the past";
}
else
{
if (date2 <= date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Return Date Cannot be Less than the Departure Date";
}
else
{
cmd2.CommandText = "insert into flight(airline_id,flight_number,numer_seats,departure_city,destination_city,departure_time,arrival_time,departure_date,arrival_date) values( '" + DropDownList_AirlineId.SelectedValue + "','" + TextBox_FlightNumber.Text + "','" + TextBox_NumerSeats.Text + "', '" + TextBox_DepartureCity.Text + "', '" + TextBox_DestinationCity.Text + "', '" + time1 + "', '" + time2 + "', '" + dateOnly1 + "', '" + dateOnly2 + "') ";
cmd2.ExecuteNonQuery();
Label_EditTableMessage.ForeColor = System.Drawing.Color.Green;
Label_EditTableMessage.Text = "Flight Added";
EmptyTextBoxes();
GridView_Flight.DataBind();
}
}
}
The problem is not with your code. You should change the data type of your field in the database. Instead of datetime or datetime2 you should use date.
You can refer to this article: https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-ver15#DateandTimeRelatedTopics
2 parts to this:
Your schema probably has the column data type set to DATETIME instead of just DATE which is going to cause it to store the full date and time regardless. This is the first thing I would check.
In your C# you can use the .Date property on a DateTime object to get just the date part of it. This is irrelevant if you use the correct data type for your column as per point 1
date.Date
or if you want it in string format:
date.Date.ToShortDateString()
the problem is you use
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
and previus you use
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
you are working only with date, and the datetime assume the time with 00:00:00
Related
I am getting an error
ERROR [42500] ERROR: 3020 - There was an error when converting the date value "0000-00-48. In the field "salesOrder Transaction Date
The date value I am trying to insert is 4/4/2018.
My code
DateTime JobDate = Wintac_JobDate;
string addSalesOrder = "INSERT INTO SalesOrderLine (CustomerRefListID, TemplateRefListID," +
" SalesOrderLineItemRefListID, SalesOrderLineDesc,SalesOrderLineQuantity, SalesOrderLineRate, " +
"SalesOrderLineSalesTaxCodeRefListID, Memo, SalesOrderLineInventorySiteRefListID, SalesOrderLineInventorySiteLocationRefListID" +
", TxnDate, ShipAddressAddr1, ShipAddressAddr2, ShipAddressAddr3, ShipAddressAddr4, ShipAddressAddr5, FQSaveToCache)" +
"VALUES('" + QBCustomerListID + "','" + templateLID + "', '" + LID + "', '" + Description + "', " + Quantity + ", " + 120 + "," +
" '" + SalesTax + "', '" +Wintac_WipNo+"','"+LaborSite+"','"+LaborSiteLocation+"',"+
"?,'" + shipAdr1+ "','" + shipAdr2 + "','" + shipAdr3 + "','" + shipAdr4 + "','" + shipAdr5 + "'," +
""+ FQSaveToCache + ")";
OdbcCommand sqlcmd2 = new OdbcCommand(addSalesOrder, quickbookscon2);
sqlcmd2.CommandType = CommandType.Text;
sqlcmd2.CommandTimeout = 180;
MessageBox.Show(JobDate.ToShortDateString());
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate
if (Quantity != 0)
{
if (sqlcmd2.ExecuteNonQuery() == 1)
{
if(FQSaveToCache == 0)
MessageBox.Show(" added successfully.");
}
}
sqlcmd2.Dispose()
I have tried converting the variable Job Date
Date Time
short date string
long date string
entering the variable directly into the query
Any help would be appreciated.
I think the main problem is on that line;
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate.ToLongDateString()
You try to insert string representation on a DateTime typed column. That's quite wrong. You need to directly pass your DateTime value instead of passing it string representation. To learn this as a habit, please read Bad habits to kick : choosing the wrong data type
Other than this, I saw a few problem also in your code:
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection and commmand automatically instead of callind Dispose method manually which you didn't even consider to do in your code.
I am inserting data into MySql from C# code in Windows Forms application. This work fine on my development machine. when I move the code to other machine to test I get the error of
string was not recognized as valid datetime
I have tried with every solution TryParse, ParseExact, TryParseExact even Convert function. in last I tried to done with direct in query to skip further problems.
string dd = row["TIMESTAMP1"].ToString(); // 14-Nov-2018 02:25:00 AM
DateTime dt1 = DateTime.ParseExact(dd, "dd-MMM-yy h:mm:ss tt", null);
//string date2 = dt1.ToString("yyyy-MM-dd hh:mm:ss");
string y = dt1.Year.ToString();
string m = dt1.Month.ToString();
string d = dt1.Day.ToString();
string h = dt1.Hour.ToString();
string i = dt1.Minute.ToString();
string s = dt1.Second.ToString();
string dte = y + "," + m + "," + d + "," + h + "," + i + "," + s;
//DateTime.TryParseExact(date2, "yyyy-MM-dd hh:mm:ss", new CultureInfo("en-US"), DateTimeStyles.None, out dateDb);
//DateTime date3 = DateTime.Parse(date2, "yyyy-MM-dd hh:mm:ss");
string query = "INSERT INTO transaction (transid, ticketid, storeid, TIMESTAMP, transtypeid, total) Values ('" + row["transid"] + "','" + row["ticketid"] + "','" + Convert.ToInt32(row["storeid"]) + "',STR_TO_DATE('"+dte+ "', '%Y,%m,%d,%h,%i,%s'),'" + Convert.ToInt32(row["transtypeid"]) + "','" + Convert.ToDecimal(row["total"]) + "')";
How do I make this possible to work on other machines without exceptions. It works fine on development machine.
Update
tried with parameters too
cmd.Parameters.Add(new MySqlParameter("#date", date2)).MySqlDbType = MySqlDbType.DateTime;
It is possible to auto-increment datetime which I parse from daterangepicker to add AddDays(7) and then insert it to DB?
string strValue = Page.Request.Form["daterange"];
string strValue2 = Page.Request.Form["daterange2"];
DateTime myDate = DateTime.Parse(strValue);
DateTime myDate2 = DateTime.Parse(strValue2);
queryStr = "INSERT INTO `wp_reservations` ( `arrival`, `departure`, `user`, `name`, `email`, `country`, `approve`, `room`, `roomnumber`, `number`, `childs`, `price`, `custom`, `customp`, `reservated`) VALUES ('" + strValue + "INTERVAL 7 DAY', '" + strValue2 + "', 0, '" + DropDownList1.SelectedItem.Text + "', '" + emailValue + "', 'SI', '" + DropDownList2.SelectedValue + "', '" + DropDownList3.SelectedValue + "', '1', 10, 0, '0;0', '', '', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt") + "');";
You can use
DATE_ADD(NOW(), INTERVAL 7 DAY) in insert query
If u want to do this in code see Datetime in C# add days
U can also do it in DAO query see DATEADD (Transact-SQL)
I have a database ShiftChange, and the fields are
Fromdate='09/11/2014', Todate='11/11/2014',Shift='MG' and Month='11'(dd/MM/YYYY format)
Fromdate='11/11/2014', Todate='15/11/2014',Shift='AF' and Month='11
I want to find today's shift from these table. I tried like this,
DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("dd/MM/yyyy");//system date converted to given format
int month = DateTime.Now.Month;
string str = "Select Min(Fromdate), Max(Todate) From ShiftChange where Month='" + month + "'";
SqlDataReader dr = conn.query(str);
if (dr.Read())
{
string mindate = dr[0].ToString();
string maxdate = dr[1].ToString();
string str3 = "select Shift from ShiftChange where '" + s_today + "' >= '" + mindate + "' and '" + s_today + "' <= '" + maxdate + "' and Month='"+month+"'";//checks current shift type of selected date.
SqlDataReader dr3 = conn.query(str3);
if (dr3.Read())
{
string shiftid = dr3[0].ToString();
}
Here connection is my connection class and query is my (sqldatareader dr) method.When I run this query I am getting shiftName 'MG' but actually the shiftName correspondent to today's date is 'AF' but it not getting. I hope it is my query's issue. Please show me the error
First of all you should make your query parameterized or you can prepare sql stored procedure and use that stored procedure in your code. I am giving you sql code for stored procedure here.
declare #month varchar(50) = '11'
declare #mindate varchar(50)
declare #maxdate varchar(50)
declare #date varchar(50)
select #mindate=min(fromdate),#maxdate = max(todate)
from ShiftChange Where Month = #month
select TOP 1 Shift From ShiftChange
WHERE #date>= fromdate and todate<=#date
and month = #month
order by todate desc
Btw, it's always better to use datatype date or datetime when dealing with dates.
I solved this issue with #Mukund's help. I applied his code in my project like this,
DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("dd/MM/yyyy");
int month = DateTime.Now.Month;
string str = "Select Min(Fromdate), Max(Todate) From ShiftChange where Month='" + month + "'";
SqlDataReader dr = conn.query(str);
if (dr.Read())
{
string mindate = dr[0].ToString();
string maxdate = dr[1].ToString();
string str3 = "select TOP 1 Shift From ShiftChange WHERE '"+s_today+"'>=Fromdate and Todate>='"+s_today+"' and month = '"+month+"' order by Todate desc";
SqlDataReader dr3=conn.query(str3);
if(dr3.Read())
{
string shift = dr3[0].ToString();
}
I'm building a web application in asp.net using C# and postgreSQL database. The application is a booking system for appointments.
In a listbox I print the date, time and name of a certain appointment. I get get the date, time and name from the database.
My problem is that the date and time displays in long format, see picture below.
I want to display date in format 2014-04-22 and time in format 08:00.
My code:
string sql = "SELECT date, time, name FROM tbl_app WHERE id = '" + id + "'";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
Listbox.Items.Add(dr["date"] + " " + dr["time"] + " " + dr["name"]);
}
Not really sure how the formatting could be done at Postgres end, but the fields appear to be of type DateTime, you can format the DateTime objects in your C# code like:
while (dr.Read())
{
//Check for DBNull.Value
DateTime date = Convert.ToDateTime(dr["date"]);
DateTime time = Convert.ToDateTime(dr["time"]);
Listbox.Items.Add(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " "
time.ToString("HH:mm", CultureInfo.InvariantCulture) + " "
+ dr["name"]);
}
Consider using parameter with your Query instead of concatenating your query. This is prone to SQL Injection. You may see: Custom Date and Time Format Strings
You can use ToShortDateString and ToShortTimeString which work on strings, which is why I used ToString on the DataReader items
while (dr.Read())
{
Listbox.Items.Add(dr["date"].ToString().ToShortDateString() + " " + dr["time"].ToString().ToShortTimeString() + " " + dr["name"]);
}
http://msdn.microsoft.com/en-us/library/system.datetime.toshorttimestring.aspx
http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx
Edit
As the comment points out ToShortDateString does exist on Strings, instead it's applied to DateTime values... Code updated to show how
while (dr.Read())
{
Listbox.Items.Add(
DateTime.Parse(dr["date"].ToString()).ToShortDateString() + " " +
DateTime.Parse(dr["time"].ToString()).ToShortTimeString() + " " +
dr["name"]);
}