get number of hours between two date and two Time - sql

I have a DataGridView contains all the spots with (DateStarttasck, TimeStarttasck) and (DateEndtasck, TimeEndtask) made ​​in a given period (StartDate, EndDate), and I try to calculate the number of hours between (DateStarttasck, TimeStarttasck) and (DateEndtasck, TimeEndtask) during the period (StartDate, EndDate)
NB: DateStarttasck, TimeStarttasck are each separated in DateTimePicker
and same thing for (DateEndtasck, TimeEndtask) (StartDate, EndDate)
so I'm looking at first to do a combinaision between Time and date and then calculate the number of hours
Dim sql As String = "select * from task where id_task = " & Textbox1.Text & " and Datetasck Between '" & DateTimePicker1.Text & "' And '" & DateTimePicker2.Text & "';"
command.CommandText = sql
connection.Open()
Dim ds As New DataSet
Dim SQLAdapter As New MySqlDataAdapter(sql, connStr)
SQLAdapter.Fill(ds, "connectString")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "connectString"
DataGridView1.AutoResizeColumns()
connection.Close()

Use DateTime.TryParse to attempt to convert the date string and time string into a single DateTime object, like this:
Dim dateValue As Date
If Date.TryParse(dateString + " " + timeString, dateValue) Then
' Successfully parsed date and time strings into the dateValue object
Else
' Unable to parse date and time strings
End If
Note: dateString is the date piece from the database and timeString is the time piece from the database.

First of all, add both date and time (start with start) and (end with end)
ex: IN C#
DateTime date_Start = DateTime.Parse(StartDate_txt.Text);
DateTime Time_Start = DateTime.Parse(StartTime_txt.Text);
date_Start.AddHours(double.Parse(Time_Start.Hour));
DateTime date_End = DateTime.Parse(EndDate_txt.Text);
DateTime Time_End = DateTime.Parse(EndTime_txt.Text);
date_End.AddHours(double.Parse(Time_End.Hour));
float Diff = date_End.Subtract(date_Start).Hours
i hope you got the idea sorry,it's in c# but hopefully you get the idea and it's same way in vb

Related

Extract only time from database where time is saving along with date in gridview

What should I use to get only time in gridview
I want to fetch only 03:42 but getting 01-01-1900 03:42:00 how to do this
This is code
cmd.CommandText = "select bumker1 Bumker_1, bumker2 Bumker_2, bumker3 Bumker_3, silo Silo_No, start_time Drier_Strt_Time,
end_time End_Time, hexa_resol Hexa_Sol_Prep, hexa_used Hexa_Used, batch_coated Coated_Batch, resin_used Resin_Used, sand_quantity Make
from mm_sandPreparation s
where date='" & Format(CDate(sanddate.Text), "MM/dd/yyyy") & "' and shift='" & rblshift.SelectedValue & "' "
Using sda As New SqlDataAdapter()
sda.SelectCommand = cmd
Using dt As New DataSet()
sda.Fill(dt)
vw_sand_details.DataSource = dt
vw_sand_details.DataBind()
End Using
End Using
SELECT CONVERT(VARCHAR(5), GETUTCDATE(), 108)
will return the output in HH:MM format as 07:26
So in your query
SELECT CONVERT(VARCHAR(5), start_time, 108)
will return the datetime into HH:MM format

select records which will be ended after 2 days

I need to get the records that will be ended after two days
but always I got an empty datagridview.
I have tried this code:
Dim after2days As Date = Today.Date.AddDays(3)
Dim sqlstr As String = "SELECT * FROM tblvac where vend between " & Today.Date & " and " & after2days & " "
Dim da As New OleDbDataAdapter(sqlstr, Conn)
ds.Reset()
da = New OleDbDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Conn.Close()
Why is this happening and how can I fix it?
Access SQL includes functions, Date() and DateAdd(), which can give you the date range you want for your query.
Dim sqlstr As String = "SELECT * FROM tblvac where vend between Date() and DateAdd('d', 3, Date());"
If you prefer to pass date values from your VB.Net code to the db engine, use a parameter query so that you needn't bother about date format and delimiters. Just supply valid Date/Time values for the parameters.
You are building your query as a string and thus need to use the convert to date function... for MS Access its DateValue see http://www.techonthenet.com/access/functions/date/datevalue.php
Try
Dim sqlstr As String = "SELECT * FROM tblvac where vend between
DateValue('" & Today.Date & "') and DateValue('" & after2days & "') "
As commented by HansUp... this solution needs to have the date format as mm/dd/yyyy or yyyy-mm-dd

Converting Date to string with DateTimePicker

Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + DateTimePicker2.Value.ToShortDateString() + "' AND '" + DateTimePicker3.Value.ToShortDateString() + "';"
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "old_table")
connection.Close()
I have 2 DateTimePickers of format Short. In SQL, the column name "inputdate" of DataType: date.
When I choose dates with days <= 12, everything is working fine. When I choose dates with days > 12, I am having this error. I can see it's a matter of day and month but i'm still can't get the solution.
Any help is really appreciated": Conversion failed when converting date and/or time from character string.
I advice you to use the Parameter to use SqlDbType.DateTime and then pass the DateTime directly to the parameter (do not need to convert) , and also avoid SQL injections , like this :
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN #startDate AND #endDate;"
Dim cmd As New SqlCommand(sql, connection)
cmd.Parameters.Add("#startDate", SqlDbType.DateTime).Value = DateTimePicker2.Value
cmd.Parameters.Add("#endDate", SqlDbType.DateTime).Value = DateTimePicker3.Value
Dim dataadapter As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "old_table")
connection.Close()
the output format of ToShortDateString() is not valid for sql server, and sql mixes the days with months.
try this
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + DateTimePicker2.Value.ToString("yyyy-MM-dd") + "' AND '" + DateTimePicker3.Value.ToString("yyyy-MM-dd") + "';"
read this more more information.
Try this:
Dim dt1 as sring = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(DateTimePicker2.Value.ToShortDateString()))
Dim dt2 as sring = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(DateTimePicker3.Value.ToShortDateString()))
Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + dt1 + "' AND '" + dt2 + "';"
Dim dataadapter As New SqlDataAdapter(sql, connection)
The basic solution is that you have to provide date into either mm/DD/YYYY format or in YYYY-MM-DD date format into ms-sql query.
So, before passing date to query convert your date into either mm/DD/YYYY format or in YYYY-MM-DD format.

VBA variable in SQL date query

I'm trying to query the SQL database for all lines where the date is after a date given through user input. I've run into a variety of errors from "incorrect syntax near" when I surround my date with "#" to "arithmetic overflow error converting expression to". My current code looks like this:
inputdate = InputBox("Please enter the starting date (mm/dd/yyyy)")
Debug.Print inputdate
querydate = "(DTG > " & Format(inputdate, "MMDDYYYY") & ")"
select StationID, DTG, CeilingFeet from SurfaceOb where " & querydate & " and StationID = 'NZWD'"
DTG is the column name for the date-time group in the SQL database. Any idea where I am going wrong? I've tried every solution I could find over the past few days without luck. Thank you in advance.
The primary issue is that dates must be enclosed in single-quotes. Here is a complete working example (minus a valid connection string) that should explain how to achieve your objective. Note that you will also want to switch to the ISO date format, in which the order is Year-Month-Day (YYYY-MM-DD).
Sub UpdateRecords()
Dim connection As New ADODB.connection
Dim recordset As New ADODB.recordset
Dim connectionString As String
Dim query As String
Dim inputdate As Date
Dim querydate As String
inputdate = InputBox("Please enter the starting date (mm/dd/yyyy)")
querydate = "(DTG > '" & Format(inputdate, "yyyy-mm-dd") & "')"
query = "select StationID, DTG, CeilingFeet from SurfaceOb where " & querydate & " and StationID = 'NZWD'"
connectionString = "..."
connection.Open connectionString
recordset.Open query, connection
ActiveSheet.Range("A1").CopyFromRecordset recordset
End Sub
Dates for SQL Server should be formatted as a date or date/time, qualified with single-quotes:
Date in ISO unseparated date format
querydate = "(DTG > '" & Format(inputdate, "yyyymmdd") & "')"
Date/Time in ISO 8601 format
querydate = "(DTG > '" & Format(inputdate, "yyyy-mm-ddThh:mm:ss.000") & "')"
Date format for MySQL is YYYY-MM-DD.
Also, as DTG is datetime, you'll need DATE(DTG) > DATE(NOW()) for example - DATE() is a MySQL function that checks only the date portion of a datetime stamp.
Your query should look like this:
querydate = "(DATE(DTG) > " & Format(userinput, "YYYY-MM-DD") & ")"
select StationID, DTG, CeilingFeet from SurfaceOb where " & querydate & " and StationID = 'NZWD'"

Date to string conversion

Dim data1 As String
Dim conn1 As SqlConnection
Dim cmd1 As New SqlCommand
Dim ada1 As New SqlDataAdapter()
Dim ds1 As New DataSet
data1 = lbldmdate.Text.ToString()
conn1 = New SqlConnection("Persist Security Info=false;User Id=justin;Data Source=ARULJUSTIN\SQLEXPRESS;Initial Catalog=firemaintain;Integrated Security=True;Pooling=False")
conn1.Open()
ada1 = New SqlDataAdapter("select Recordno, uhnumber,uhbuilding,uhlocation from hydrantmaintain WHERE unndate= '" & Today.ToString("dd/mm/yyyy") & "'", conn)
ada1.Fill(ds1)
dgnxtmdates.DataSource = ds1.Tables(0)
I am getting an error: "cannot convert from date to string"
As #Nawful pointed out, you are using "mm" (minutes) instead of "MM" (months) but it also looks like you month and day are reversed. Now, this is dependant upon your region settings for dates and specifically how you configured the SQL server but to avoid these issues, I like to do this for dates:
CONVERT(datetime, '" & Format(Value, "yyyy-MM-dd") & " 00:00:00', 102)
and this for Date and Time:
CONVERT(datetime, '" & Format(Value, "yyyy-MM-ddTHH:mm:ss") & "', 126)
Note, Value is a date or datetime data type.
In your example, it would be something like this:
ada1 = New SqlDataAdapter("select Recordno, uhnumber,uhbuilding,uhlocation from hydrantmaintain WHERE unndate= CONVERT(datetime, '" & Format(Today, "yyyy-MM-dd") & " 00:00:00', 102)", conn)
Hard to point out, but your string formatting should be dd/MM/yy. mm corresponds to minutes component.
Today.ToString("dd/MM/yyyy");
If unndate is the datetime data type in the database, you don't need to convert Today to string when querying the database.
Cause, Today is already a DateTime.
But, if unndate is a string datatype, varchar or nvarchar for example, my only advice is to use the datatype datetime for the unndate value in the first place if you want to query like that.