Compare Datetime.now to date on SQL table - c#

I'm trying to write code on c# that will compare between date that i have on SQL table (table:items, column "endTime") against datetime.now and by the result - display image.
example:
if the time on the column table is before the time now.. so display on the aspx image1, else display image2.
i've tried to do that by sql command:
private DateTime endTime(out int lastDate)
{
SqlConnection connection = new SqlConnection("Data Source=******;Initial Catalog=******;User ID=*****;Integrated Security=False;");
string commandtext = "SELECT TOP(1) endTime FROM items";
SqlCommand command = new SqlCommand(commandtext, connection);
connection.Open();
SqlCommand command2 = new SqlCommand(commandtext, connection);
lastDate = (int)command2.ExecuteScalar();
connection.Close();
return ...
}
but i have problem with the return, and with the execution of the method... :
int d;
Console.WriteLine(endTime(out d));
if (d < DateTime.Now)
{
image1.Visible = true;
}
else
{
image2.Visible = true;
}
Console.WriteLine(d);
but i got error, but i believe it's come from the return.

Instead of if (d < DateTime.Now) use this: if (d < DateTime.Now.Date)

Shouldn't you be casting out a DateTime from your query and not an int? Also, the stack trace/debugger should give you the line number of the exception. Can you post the stack trace?

What is returned by your sql query (I believe ticks)?
How do you convert int into DateTime, show a code please
Enclose SqlConnection in using() block as shown below:
using (SqlConnection connection = new SqlConnection(...))

i would suggest letting the database do the date comparison right in the sql.
SYSDATE can be compared to EndTime right in the query, and you can either not bring back rows that dont match (which allows you to process every row in the result set equally) or you check a simple value in the return set to see if the time is in the right period.

Related

How to properly convert query into DateTime in asp.net?

In my app, I am trying to grab a date from the database and compare it against local time. Right now I am getting an error when I am converting to date incorrectly.
I have tried:
Convert.ToDateTime()
DateTime.ParseExact()
My code:
string time = "Select top(1) DATE from SERVICE order by DATE desc";
SqlCommand command = new SqlCommand(time, connection);
connection.Open();
using (SqlDataReader timereader = timecommand.ExecuteReader())
{
while (timereader.Read())
{
if (DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss", null).AddMinutes(10) > currenttime)
{
// code
}
}
connection.Close();
}
I am hoping when I retrieve this value from the database, I can convert it into a proper datetime value and compare against local time and run other code after that.
At the moment I am just getting this error:
The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
I'm probably just dumb and missing something obvious..
Your query selects a single value. Use ExecuteScalar and cast it to a DateTime (it's already a DateTime, but boxed inside an object):
string time = "Select top(1) DATE from SERVICE order by DATE desc";
SqlCommand command = new SqlCommand(time, connection);
connection.Open();
DateTime d = (DateTime)command.ExecuteScalar();
connection.Close();
After you do this, and before you embark on some long mission of this protracted way of getting data out of a database, converting it to objects for use in your app etc, take a look at least at an ORM called Dapper, if not Entity Framework. Dapper's basically what you're doing now, but it auto converts your queries to objects and back and saves a lot of tedious code. With Dapper it'd look more like:
using (var connection = new SqlConnection("connstr"))
{
var d = connection.QuerySingle<DateTime>("SELECT TOP 1 Date FROM ...");
}
Yes, it's not much of a saving over what you have now, right? But what if you have a list of Order that themselves have 20 properties:
using (var connection = new SqlConnection("connstr"))
{
var orders = connection.Query<Order>("SELECT * FROM order WHERE customerID = #custid", new {custid = 123}).ToList();
}
Orders is now a list of Order objects for customer 123, parameterized, injection safe, quick and a one liner to read and populate your orders; doing that in a datareader is going to take at least 25 lines of boring code
http://dapper-tutorial.net and spend 2 minutes reading; I'll lay bets you'll be glad you did
Just try to read the value as a proper, native DateTime type like this (assuming that the DATE column in SQL Server is in fact a DATETIME or similar datatype - not a string - hopefully!):
using (SqlDataReader timereader = timecommand.ExecuteReader())
{
while (timereader.Read())
{
// just read the DateTime value as such
DateTime dt = timereader.GetDateTime(0);
// then do whatever you need to do with this DateTime value .....
}
connection.Close();
}

How do I convert a cell that has only a year (probably a string) into DateTime datatype?

I've got cells in an excel file that contain data like:
"2006","2005","2015"
It is read into a datagridview temporarily, which is later inserted into an access database like so:
using (OleDbConnection conn = new OleDbConnection(Con))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText =
"Insert INTO ACTB (ID,Business,Account,Description,Span_Year,Period,Amount_PHP,Project_Number,Status_Regime,Department,Description_Dept,Accounts,Class) " +
"VALUES(#ID,#Business,#Account,#Description,#Span_Year,#Period,#Amount_PHP,#Project_Number,#Status_Regime,#Department,#Description_Dept,#Accounts,#Class)";
for (int s = 0; s < DGVExcel.Rows.Count; s++)
{
cmd.Parameters.Clear();
int theDoubleDate = Convert.ToInt32(DGVExcel.Rows[s].Cells[4].Value);
DateTime theDate = DateTime.FromOADate(theDoubleDate);
cmd.Parameters.AddWithValue("#ID", DGVExcel.Rows[s].Cells[0].Value);
cmd.Parameters.AddWithValue("#Business_Unit", DGVExcel.Rows[s].Cells[1].Value);
cmd.Parameters.AddWithValue("#Account", DGVExcel.Rows[s].Cells[2].Value);
cmd.Parameters.AddWithValue("#Description", DGVExcel.Rows[s].Cells[3].Value);
cmd.Parameters.AddWithValue("#Span_Year", theDate);
cmd.Parameters.AddWithValue("#Period", DGVExcel.Rows[s].Cells[5].Value);
cmd.Parameters.AddWithValue("#Amount_PHP", DGVExcel.Rows[s].Cells[6].Value == null ? 0 : Convert.ToDouble(DGVExcel.Rows[s].Cells[6].Value));
cmd.Parameters.AddWithValue("#Project_Number", DGVExcel.Rows[s].Cells[7].Value);
cmd.Parameters.AddWithValue("#Status_Regime", DGVExcel.Rows[s].Cells[8].Value);
cmd.Parameters.AddWithValue("#Department", DGVExcel.Rows[s].Cells[9].Value);
cmd.Parameters.AddWithValue("#Description_Dept", DGVExcel.Rows[s].Cells[10].Value);
cmd.Parameters.AddWithValue("#IS_Accounts", DGVExcel.Rows[s].Cells[11].Value);
cmd.Parameters.AddWithValue("#ITR_Class", DGVExcel.Rows[s].Cells[12].Value);
cmd.ExecuteNonQuery();
}
}
}
However, these write the values wrong, like 8/7/1905 all ending in 1905.
Another requirement is that the end value be day and month agnostic, meaning the value would come up as say: 2016 => 1/1/2016, just before the data is inserted into the database. Some have suggested that I merely use int values, however, datetime is required for me because I intend to use the between keyword to easily look up data between certain periods.
Edit: I just realized that some of my data might not have a year listed. Normally, I could be able to insert nulls just fine, however, if I'm doing some convert before that, I'm sure it will throw an exception like Cannot convert DB.Null into other types.
You can check if there is a value in the cell and then create a new DateTime
if (string.IsNullOrEmpty(DGVExcel.Rows[s].Cells[3].Value))
{
cmd.Parameters.AddWithValue("#Span_Year", DateTime.Now.Date);
}
else
{
cmd.Parameters.AddWithValue("#Span_Year", new DateTime(Convert.ToInt32(DGVExcel.Rows[s].Cells[3].Value), 1, 1);
}
I would also recommend specifying the datatype in the parameter, this will provide more type-safety and prevent conversion errors with datetime.
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = 45;
cmd.Parameters.Add("#Span_Year", SqlDbType.DateTime).Value = date;

MySQL select now()

I'm trying to get time from my database.
string result;
using (MySqlConnection connection = new MySqlConnection("Server=localhost;Database=database;Uid=root;Pwd='';"))
{
string sql = "select now()";
MySqlCommand cmd = new MySqlCommand(sql, connection);
connection.Open();
result = (string)cmd.ExecuteScalar();
connection.Close();
}
DateTime now = DateTime.ParseExact(result, "yyyy-MM-dd HH:mm:ss", null);
metroLabel4.Text = (newtime);
This is the code I'm using and when I build my program It gives error for result = (string)cmd.ExecuteScalar(); this line.
Looks like MySQL Now() returns date and time and this type mapped with DateTime in .NET side.
Since ExecuteScalar returns object, you can explicitly cast it to DateTime and it should be fine.
DateTime result;
...
result = (DateTime)cmd.ExecuteScalar();
A few things more;
Use using statement to dispose your command as well.
Since you use using statement, your connection.Close() line is unnecessary. That statement close your connection automatically.
You don't need parsing anymore. Just assing DateTime now = result;
It is not clear what is newtime exactly but after that, you can assign it as metroLabel4.Text = now.ToString() or whatever you format with ToString(string) overload.

How to insert a time column into SQL Server

Using Visual Studio 2010 and C#
Table1:
column datatype
------------------------
Currenttime time
How to insert a time value into table1?
Code
string hr = txtHr.Text;
string min = txtMin.Text;
string time = hr + ":" + min;
insert into table1 values(time)
Getting error
Cannot convert from string to System.Timespan
while inserting into table1.
Need Code help
You should always (no exceptions!) use parametrized queries instead of constructing your own SQL statement as a string! Just google "SQL injection" - it's a really horrible thing.... stop doing that RIGHT NOW
To use a parametrized query, you should get in the habit of using a pattern like this:
// Define your SQL query - WITH parameters!
// And always specify the list of columns for your INSERT!
string query = "INSERT INTO dbo.Table1(CurrentTime) VALUES(#TimeValue)";
// use the "using" blocks to properly protect your disposable connection and command
using (SqlConnection con = new SqlConnection("server=.;database=test;integrated security=SSPI;"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
string hr = txtHr.Text;
string min = txtMin.Text;
string time = hr + ":" + min;
// set the parameter value
cmd.Parameters.Add("#TimeValue", SqlDbType.Time).Value = TimeSpan.Parse(time);
// open connection, execute your INSERT, close connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
You need DateTime.Parse and not Timespan.parse , Timespan represents length of time
You need to parse to DateTime and not datetimepicker's itself, parse its value
DateTime.Parse(datetimepicker1.value)

How to run query on date time colomn

Trying to retrieve records by passing date in where condition, i am sending date by using date time picker but at the end reader not showing any record.
I did conversion of date time as Convert(char(10),ext_date,101) still facing the same problem.
string str=#"select * from extra_expense where CONVERT(char(10),ext_date,101) = #date";
sqlcommand = new SqlCommand(str,sqlconnection );
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetimepicker1.value);
datareader = sqlcommand.ExecuteReader();
List<Projects> projects = new List<Projects>();
while (datareader.Read())
{
Projects proj = new Projects();
proj.expenseid = Convert.ToInt32(datareader.GetValue(0));
proj.ProjectDate = Convert.ToDateTime(datareader.GetValue(1));
projects.Add(proj);
}
datareader.Close();
return projects;
You can specify dates as strings in T-SQL, like so:
SELECT MyFields FROM MyTable
WHERE StartDate >= '01-01-00' AND StartDate <= '12-31-00'
You shouldn't cast the field in the table, you should cast the parameter to the correct type. In fact, you are already casting it because the parameter is declared as datetime, but on your query you are forcing ext_date to char(10).
Try this:
string str=#"select * from extra_expense where ext_date = #date";
along with
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetime.Parse( datetimepicker1.value);

Categories

Resources