I have a string date in database. I did like below mentioned format but it shows error like
input string was not in a correct format
But when I referred with internet this method is correct but it does not work for me. Let me know the reason?
string str1 = "select todate from Employee where EmpCode='" + code + "'";
SqlDataReader dr1 = conn.query(str1);
if (dr1.Read())
{
string todate1 = dr1[0].ToString();
int todate2 =Convert.ToInt32(todate1);
}
It sounds like you should be using a DateTime column in the database, at which point there's no need for integers or strings:
var today = DateTime.Today; // Or maybe use DateTime.Now
// Use parameterized SQL rather than string concatenations
string sql = "select todate from Employee where EmpCode=#EmpCode";
using (var conn = new SqlConnection(...))
{
conn.Open();
using (var command = new SqlCommand(sql, conn))
{
command.Parameters.Add("#EmpCode", SqlDbType.VarChar).Value = code;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
DateTime date = reader.GetDateTime(0);
if (today > date)
{
// Do something
}
}
}
}
}
If your date really is being stored as a string and you can't change that (and if you can, then definitely do so), you can use DateTime.ParseExact instead:
// Other code as before
while (reader.Read())
{
DateTime date = DateTime.ParseExact(reader.GetString(0),
"yyyy-MM-dd", // Or whatever the format is
CultureInfo.InvariantCulture);
if (today > date)
{
// Do something
}
}
Note that in both cases, this uses the system local time zone. You may want to consider storing all values in UTC, and performing all calculations that was as well - in which case you can use DateTime.UtcNow.
Related
I am using a query to select data from sql database. It has rows but data raader.Read() function returns false and rows are empty as I have checked in debugging
Code that i have been using is
public void getSale()
{
DB db = new DB();
try
{
db.cmd.CommandText = "select * from Sale where date is not null and (date between '"+StartDate+"' and '"+EndDate+"') order by date";
db.cmd.Connection = db.con;
db.con.Open();
if(db.con.State == System.Data.ConnectionState.Open)
{
db.dataReader = db.cmd.ExecuteReader();
if(db.dataReader.HasRows)
{
while(db.dataReader.Read())
{
SaleModel sm = new SaleModel();
sm.SaleId = long.Parse(db.dataReader["Id"].ToString());
sm.UserName = db.dataReader["UserName"].ToString();
sm.ItemsQuantity = int.Parse(db.dataReader["ItemsQuantity"].ToString());
sm.TotalAmount = double.Parse(db.dataReader["TotalAmount"].ToString());
sm.SubTotal = double.Parse(db.dataReader["SubTotal"].ToString());
sm.Discount = double.Parse(db.dataReader["Discount"].ToString());
sm.Completed = bool.Parse(db.dataReader["Completed"].ToString());
sm.Date = DateTime.Parse(db.dataReader["Date"].ToString());
sm.CustomerPhone = long.Parse(db.dataReader["CustomerPhone"].ToString());
SalesList.Add(sm);
}
db.con.Close();
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
}
}
And When I tested this query on Query editor in Visual studio rows were returned
If Anyone can help?
Why you concatenate strings to build your sql query? NEVER do that. It is a source for sql-injection and can cause issues like this. Instead use parameterized queries.
Also don't use SqlConnection wrappers like your DB class. That can cause several other issues. Instead create, open, close and dispose them where you need them, best by using the using-statament. The connection-pooling will manage the rest for you.
public List<SaleModel> GetSale(DateTime startDate, DateTime endDate)
{
string sql = #"select * from Sale
where date is not null
and date between #StartDate and #EndDate
order by date";
var salesList = new List<SaleModel>();
try
{
using (var con = new SqlConnection("insert your connection string"))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = endDate;
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
SaleModel sm = new SaleModel();
sm.SaleId = long.Parse(reader["Id"].ToString());
sm.UserName = reader["UserName"].ToString();
sm.ItemsQuantity = int.Parse(reader["ItemsQuantity"].ToString());
sm.TotalAmount = double.Parse(reader["TotalAmount"].ToString());
sm.SubTotal = double.Parse(reader["SubTotal"].ToString());
sm.Discount = double.Parse(reader["Discount"].ToString());
sm.Completed = bool.Parse(reader["Completed"].ToString());
sm.Date = DateTime.Parse(reader["Date"].ToString());
sm.CustomerPhone = long.Parse(reader["CustomerPhone"].ToString());
salesList.Add(sm);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
}
return salesList;
}
I'm pretty sure that this works(f.e. can be a localization issue).
Side-note: a method GetSale should return a List<SaleModel> but not fill one. You should also pass the parameters as DateTime to the method. I've changed it in my code sample.
This is a much better way to structure you code, and there's a good chance it will fix your issue, too:
//accept the date values as parameter arguments, return the result.
// Do NOT mess about with variables at the global or class scope.
public IEnumerable<SalesModel> getSale(DateTime StartDate, DateTime EndDate)
{
string sql = "select * from Sale where date is not null and (date between #StartDate and #EndDate) order by date";
//DON'T abstract SqlCommand/SqlConnection. DO abstract your connection string.
//Also, don't bother with the try/catch at this level. You can't really do anything with it here, so worry about the exception in calling code.
using (var cn = new SqlConnection(DB.ConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = StartDate
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = EndDate
cn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
var sm = new SaleModel();
//If you have good schema design, these values are **already** in the correct type.
// The old code forces an expensive conversion to string, following by an expensive parse back to the type it already had.
// We can do MUCH better.
sm.SaleId = (long)rdr["Id"];
//but it is okay for types that are *already* strings
sm.UserName = rdr["UserName"].ToString();
sm.ItemsQuantity = (int)rdr["ItemsQuantity"];
sm.TotalAmount = (double)rdr["TotalAmount"]);
sm.SubTotal = (double)rdr["SubTotal"];
sm.Discount = (double)rdr["Discount"];
sm.Completed = (bool)rdr["Completed"];
sm.Date = (DateTime)rdr["Date"];
sm.CustomerPhone = (long).rdr["CustomerPhone"];
yield return sm;
}
}
}
}
Here it is again without all the extra comments. The point here is this is still less code than the original that used string concatenation, and it took less than 10 minutes to write. Good code doesn't necessarily take longer.
public IEnumerable<SalesModel> getSale(DateTime StartDate, DateTime EndDate)
{
string sql = "select * from Sale where date is not null and (date between #StartDate and #EndDate) order by date";
using (var cn = new SqlConnection(DB.ConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = StartDate
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = EndDate
cn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
var sm = new SaleModel();
sm.SaleId = (long)rdr["Id"];
sm.UserName = rdr["UserName"].ToString();
sm.ItemsQuantity = (int)rdr["ItemsQuantity"];
sm.TotalAmount = (double)rdr["TotalAmount"]);
sm.SubTotal = (double)rdr["SubTotal"];
sm.Discount = (double)rdr["Discount"];
sm.Completed = (bool)rdr["Completed"];
sm.Date = (DateTime)rdr["Date"];
sm.CustomerPhone = (long).rdr["CustomerPhone"];
yield return sm;
}
}
}
}
Note that I return an IEnumerable rather than a List. If you really need a List (tip: you probably don't, and sticking with IEnumerable is faster), you can just call ToList() on the result.
don't see any issue except that you are using date which is a reserve word and not your actual column name. Change your query to be
db.cmd.CommandText = "select * from Sale where [date] is not null and ([date] between '"+StartDate+"' and '"+EndDate+"') order by [date]";
How to store date as "1" and month as "1" to mysql database by using c#,(for example 1-1-1987),i can get year from the variable frdt,so i need to store for example 1-1-frdt.
string frdt = drow1["release_year"].ToString();
i would pass it into a DateTime object and insert that one into your database
string frdt = drow1["release_year"].ToString();
DateTime Result = new DateTime(int.Parse(frdt), 1, 1);
string Command = "INSERT INTO TABLENAME (COLUMNNAME) VALUES (#DATEVALUE);"; // TODO
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
mConnection.Open();
using (MySqlCommand myCmd = new MySqlCommand(Command, mConnection))
{
myCmd.Parameters.AddWithValue("#DATEVALUE", Result);
int RowsAffected = myCmd.ExecuteNonQuery();
}
}
If you're storing a date then it should be stored as a binary date, not as text. It's hard to tell whether you're doing that or not but you absolutely should. The fact that you're storing a year, which is a number, in a string variable is not encouraging. You should be storing the year in an int and then creating a DateTime like so:
var myDate = new DateTime(year, 1, 1);
where year is the int containing the year. You then save that to your database as you would any other data, using a parameter one would hope, e.g.
var command = new MySqlCommand("UPDATE MyTable SET MyDate = #MyDate WHERE ID = #ID", connection);
command.Parameters.AddWithValue("#MyDate", myDate);
I'm attempting to compare an endDate column in a SQL Server database to a stored variable called highDate in c#.
DateTime highDate = new DateTime(2999, 1, 1);
SqlConnection myConnection = new SqlConnection("My connection string");
SqlCommand myCommand = new SqlCommand("My query including endDate_TS", myConnection);
myCommand.Connection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
DateTime endDate = new DateTime(myReader["endDate_TS"]); //something is wrong here
}
if (endDate > highDate)
{
//do something
}
How do I correctly format the endDate variable I created to accept the endDate_TS from the SQL Server database? (the endDate_TS is a SQL Server DATETIME datatype)
DateTime has several constructors but none which takes an object. But myReader["endDate_TS"] returns an object. If it's actually the number of ticks (what it seems to be if _TS means TimeSpan) you can use the constructor that takes a long:
int indexOfEndDateTsColumn = myReader.GetOrdinal("endDate_TS");
DateTime endDate = new DateTime(myReader.GetInt64(indexOfEndDateTsColumn));
However, the last sentence in parentheses suggests that it's actually a datetime in the database, then you can use DataReader.GetDateTime directly:
DateTime endDate = myReader.GetDateTime(indexOfEndDateTsColumn);
when reading SQl Date time field , only i can take the date with time ..how to get only date in to text box from Ajax or some method.
this is what i need to do
http://i.stack.imgur.com/n0fgG.jpg
that's how I'm taking the date to text box.
protected void ddlBatch_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["CBConnectionString"].ConnectionString;
const String strQuery = "select ItemIdentityCode, Qty, PurchasingPrice, ExpireDate, DiscountRate, IssueMode, Principle, Force from DEL_PurchasesLines where BatchNumber = #BatchNumber";
SqlConnection conPR = new SqlConnection(strConnString);
SqlCommand cmdPR = new SqlCommand();
cmdPR.Parameters.AddWithValue("#BatchNumber", ddlBatch.SelectedItem.Value);
cmdPR.CommandType = CommandType.Text;
cmdPR.CommandText = strQuery;
cmdPR.Connection = conPR;
try
{
conPR.Open();
SqlDataReader sdr = cmdPR.ExecuteReader();
while (sdr.Read())
{
tHFExpiaryDate.Text = sdr["ExpireDate"].ToString();
}
}
catch (Exception ex)
{
//throw ex;
}
finally
{
conPR.Close();
conPR.Dispose();
}
}
Don't convert the raw value to a string in the first place - it should already be a DateTime:
DateTime date = (DateTime) dsr["ExpireDate"];
Then you can convert it into whatever format you're interested in:
// TODO: Consider specifying the culture too, or specify a standard pattern.
tHFExpiaryDate.Text = date.ToString("MM/d/yyyy");
It's important to separate the question of "How can I get the data from the database in an appropriate type?" from "How should I present the data to the user?"
Try something like:
DateTime.ParseExact(sdr["ExpireDate"].ToString(), "MM/d/yyyy", CultureInfo.InvariantCulture)
In your sample:
tHFExpiaryDate.Text = DateTime.ParseExact( ((DateTime)dt.Rows[0][0]).ToString("MM/d/yyyy"), "MM/d/yyyy", System.Globalization.CultureInfo.CurrentCulture).ToString("MM/d/yyyy"));
This always works for me
protected String getDate(string date)
{
DateTime dDate;
string sdate = null;
if (!string.IsNullOrEmpty(date.ToString()))
{
dDate = DateTime.Parse(date.ToString());
sdate = dDate.ToString("dd/MM/yyyy");
sdate = dDate.ToLongDateString();
}
return sdate;
}
Other date format example http://www.dotnetperls.com/datetime-format
My dataset format looks like this
EMPNAME FRMDATE TODATE
ANU 01-10-2012 01-20-2012
HARI 01-05-2012 02-05-2012
Now get input through a textbox as 01-17-2012 for a specific employee.
My question is: how to check whether the i/p date is between these two columns (FRMDATE,TODATE) in the dataset?
Try This
DataRow []_dr= ds.Tables[0].Select( inputDate +">= FRMDATE AND "+inputDate +" <= TODATE");
I believe the method below will help you, for extra reading material on comparing dates have a look at these two threads:
Using linq or lambda to compare dates
Check if datetime instance falls in between other two datetime objects
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public bool IsDateInRange(string date, string employeeId)
{
DateTime dateToCompare = DateTime.MinValue;
bool isInRange = false;
if (!String.IsNullOrEmpty(date) && !String.IsNullOrEmpty(employeeId) &&
DateTime.TryParse(date, out dateToCompare))
{
DataTable table = new DataTable();
string connectionString = WebConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "SELECT TOP 1 * FROM EmployeeDates WHERE EMPNAME = #EmpName";
command.Parameters.AddWithValue("#EmpName", employeeId);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
DateTime fomDate = (DateTime)table.Rows[0]["FRMDATE"];
DateTime toDate = (DateTime)table.Rows[0]["TODATE"];
//DateTime.Ticks converts a date into long
//Now you can simply compare whether the input date falls between the required range
if (dateToCompare.Ticks >= fomDate.Ticks && dateToCompare.Ticks <= toDate.Ticks)
{
isInRange = true;
}
connection.Close();
}
}
}
return isInRange;
}
db.ClubPorsant.Where(p => p.CreateDate>= _FromDate && p.CreateDate<= _ToDate).OrderByDescending(p => p.MablaghVariz).ThenByDescending(p => p.Shomarehesab).ToList();