Remove Time from date/time vb.net - vb.net

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Form2.Show()
Form2.TextBox1.Text = dgv1.CurrentRow.Cells(0).Value.ToString
Form2.TextBox2.Text = dgv1.CurrentRow.Cells(1).Value.ToString
Form2.TextBox3.Text = dgv1.CurrentRow.Cells(2).Value.ToString
Form2.TextBox4.Text = dgv1.CurrentRow.Cells(3).Value.ToString
Form2.TextBox5.Text = dgv1.CurrentRow.Cells(4).Value.ToString
Form2.TextBox6.Text = dgv1.CurrentRow.Cells(5).Value.ToString
Form2.TextBox7.Text = dgv1.CurrentRow.Cells(6).Value.ToString
textbox5 is the one that should only show the date but when i click the button, the textbox shows me the date and time. ex: 12/01/12 12:00 AM.
how can i remove the time from showing up into the textbox?

Since the CurrentCells(4).Value is an object try casting it to a DateTime then convert using the ToShortDateString Method
Form2.TextBox5.Text = CType(dgv1.CurrentRow.Cells(4).Value, DateTime).ToShortDateString
or you can use DateTime.TryParse which will return true if the conversion is succesfull
Dim tempDate As Date
If DateTime.TryParse(CStr(dgv.CurrentRow.Cells(4).Value), tempDate) Then
Form2.TextBox5.Text = tempDate.ToShortDateString
Else
Form2.TextBox5.Text = "Invalid Date"
End If

Try...
If dgv1.CurrentRow.Cells(4).Value IsNot Nothing
Form2.TextBox5.Text = String.Format("{0:dd/mm/YYYY}", dgv1.CurrentRow.Cells(4).Value)
Else
Form2.TextBox5.Text = ""
End If

there is a datetime format function. check this http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx

I just removed the .ToString in this line:
Form2.TextBox5.Text = dgv1.CurrentRow.Cells(4).Value.ToString
When i removed the .ToString it just shows the short date in the date textbox

try this
declare MyTime as datetime
Mytime = dateadd(day, -datediff(day, 0, Date.now), Date.now)

Related

How to change 6 digit number into Date String

So, I've found this thread, which talks about my issue exactly, however the solution doesn't work for me: How to Change Format column in Datagridview to date type for this value
I've got a different number patter, in which my data is: YYMMDD, just 6 numerical digits (000901 - September 1st, 2000)
Does the data structure make a difference when converting it to a data string? Does it need to be in an initial format?
This is my current string of code:
DataGridView1.Columns(1).DefaultCellStyle.Format = "yy/MM/dd"
Just trying to get any format what-so-ever, but it just remains as 6 digits.
OK, try this. Set your format in the datagridview to the date format you want to use. For my example, I had 3 columns and the far right column contained the 6 digit strings.
In my 3rd column I set a format of yyyy/MM/dd in the datagridview.
In the button click I looped through the dgv and parsed the values to a datetime which allowed the format to work as it was now working with a date type.
For Each r As DataGridViewRow In DataGridView1.Rows
If Not r.IsNewRow Then
r.Cells(2).Value = DateTime.ParseExact(r.Cells(2).Value.ToString, "yyMMdd", CultureInfo.InvariantCulture)
End If
Next
Upon clicking the button, I got the following results.
Now that the column is a date datatype, we can just change the format and the columns format to the new format setting.
I added a second button and in that button I placed the code
DataGridView1.Columns(2).DefaultCellStyle.Format = "MMM dd, yyyy"
which immediately change the 3rd column to the new format
After some thought and experimentation, I realised how to do this on the GUI instead of when loading the data.
You can achieve this particular formatting by handling the CellFormatting event of the DataGridView.
Test Data I used:
Private Property MyData As DataTable
Private Sub InitialiseData()
MyData = New DataTable
MyData.Columns.Add("YMDString", GetType(String))
Dim dr As DataRow
dr = MyData.NewRow()
dr(0) = "000901"
MyData.Rows.Add(dr)
dr = MyData.NewRow()
dr(0) = "010901"
MyData.Rows.Add(dr)
dr = MyData.NewRow()
dr(0) = "020901"
MyData.Rows.Add(dr)
End Sub
DataGridView configuration
Private Sub SetupDataGridView()
InitialiseData()
DataGridView1.AutoGenerateColumns = False
DataGridView1.Columns.Add("YMDString", "YMD String")
DataGridView1.Columns.Add("YMDDateTime", "YMD DateTime")
DataGridView1.Columns(0).DataPropertyName = "YMDString"
DataGridView1.Columns(1).DataPropertyName = "YMDString"
DataGridView1.DataSource = MyData
AddHandler DataGridView1.CellFormatting, AddressOf DataGridView1OnCellFormatting
End Sub
And the CellFormatting event handler that does the hard work. The DateTime parsing isn't the best you can use, but it does illustrate the principal of what you want to achieve.
Private Sub DataGridView1OnCellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
Dim thisGrid As DataGridView = CType(sender, DataGridView)
If (thisGrid IsNot Nothing AndAlso e.Value IsNot Nothing) Then
If (thisGrid.Columns(e.ColumnIndex).Name = "YMDDateTime") Then
Dim stringValue As String = e.Value.ToString()
Dim year As Integer = 2000 + stringValue.Substring(0, 2)
Dim month As Integer = stringValue.Substring(2, 2)
Dim day As Integer = stringValue.Substring(4, 2)
Dim dt As New DateTime(year, month, day)
e.Value = dt.ToString("yyyy/MM/dd")
End If
End If
End Sub
When run, I get this result:
I took your six digit string and converted to a DateTime then formatted as you wished.
Dim strDate As String = "180211"
Dim myDate As New DateTime(CInt("20" & strDate.Substring(0, 2)), CInt(strDate.Substring(2, 2)), CInt(strDate.Substring(4)))
Debug.Print(myDate.ToString("yy/MM/dd"))
EDIT:
I found a better answer thanks to user1751825 at VB.NET compare date time from string format
Dim myDate As Date = DateTime.ParseExact(strDate, "yyMMdd", CultureInfo.InvariantCulture)

VB form load event based on date

I'm attempting to display a button on a secondary form in vb based on what the date is (Trying to get a reset button to show only on the last day of the year).
I've tried a few different things with the code below...
I originally put it in the Form Load Event of Form 2, no msgbox displayed, button didn't display.
I cut the code out of my project and pasted it into the Form Load Event of a new project to test it on it's own... Msgbox displayed and button displayed!! :)
This got me thinking maybe I had to put the code into the Form Load Event of the Main Form. I pasted it there and made the modifications to point to form2 (Current version of the code)....
Once again , no msgbox, no button
What am I missing?
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim date1 As String = String.Format("{0:MM/dd/yyyy}", DateTime.Now)
Dim todaysdate As String = Format(Now, "Long Date")
Dim dayofweek = todaysdate.Substring(0, todaysdate.IndexOf(","))
Dim year As String = Now.Year
Dim datecheck As String = "12/29/"
Dim datecheck1 As String = "12/30/"
Dim datecheck2 As String = "12/31/"
' Add Current Year to Date to Check variables
datecheck = datecheck + year
datecheck1 = datecheck1 + year
datecheck2 = datecheck2 + year
Dim expenddt As Date = Date.ParseExact(date1, date1, System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim expenddt1 As Date = Date.ParseExact(datecheck, datecheck,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim expenddt2 As Date = Date.ParseExact(datecheck1, datecheck1,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim expenddt3 As Date = Date.ParseExact(datecheck2, datecheck2,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
' If DEC 29 or 30 Falls Fiday, Display Reset Button
If date1 = datecheck And dayofweek = "Friday" Then
' MsgBox Used Only For Testing
MsgBox("THIS ONE WORKED!")
Form2.Reset.Visible = True
End If
If date1 = datecheck1 And dayofweek = "Friday" Then
' MsgBox Used Only For Testing
MsgBox("THIS ONE WORKED!!")
Form2.Reset.Visible = True
End If
' If it's Dec 31 and it's Not Saturday or Sunday, Display Reset Button
If date1 = datecheck2 and dayofweek <> "Saturday" and dayofweek <> "Sunday" Then
' MsgBox Used Only For Testing
MsgBox("THIS ONE WORKED!!!")
Form2.Reset.Visible = True
End If
End Sub
First things first, have a read through the documentation for the DateTime structure. You can do everything that you're trying to do without using Strings. The DateTime structure has a DayOfWeek property, and Month and Day properties that will help you here.
Secondly, the way you are using the ParseExact method is wrong (not that you should end up using it). The second parameter to the ParseExact method is the format string that you expect the date to be in (something like "MM/dd/yyyy"). Passing in a formatted date will not work, and from my experiments, will simply return the current date without any parsing occurring.
So, with all that in mind (and assuming you want to show the button on the last weekday in the year as your code suggests, and not just the last day in the year as your question stated), try something like this:
Private Sub Main_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Form2.Reset.Visible = ShouldShowResetButton(DateTime.Now)
End Sub
Private Function ShouldShowResetButton(currentDate As DateTime) As Boolean
Return GetLastWeekdayInYear(currentDate.Year) = currentDate.Date
End Function
Private Function GetLastWeekdayInYear(year As Integer) As Date
Dim lastDayInYear As Date
lastDayInYear = New Date(year, 12, 31)
Select Case lastDayInYear.DayOfWeek
Case DayOfWeek.Sunday
Return New Date(year, 12, 29)
Case DayOfWeek.Saturday
Return New Date(year, 12, 30)
Case Else
Return lastDayInYear
End Select
End Function

Validating a date in a textbox

I am trying to valid user input in a textbox which will only takes dates or an empty value (hence the textbox vs a date time picker). Here are the conditions:
Only a date value ("dd-mm-yyyy" or "dd-mm-yy)
Must contain only slashes or numbers
The date has to be on the day it is being typed in
This is what I have so far:
Private Sub tbApp1_TextChanged(sender As System.Object, e As System.EventArgs) Handles tbApp1.TextChanged
If Not Me.tbApp1.Text = String.Empty Then
If Not DateTime.TryParseExact(tbApp1.Text.Trim, formats, New Globalization.CultureInfo("en-US"), Globalization.DateTimeStyles.None, dtTemp) Then
If Not tbApp1.Text.Trim = DateTime.Today.Date Then
ErrorProvider1.SetError(tbApp1, "This is not a valid date; Enter in this format ('M/d/yyyy' or 'M/d/yy')")
End If
Else
ErrorProvider1.Clear()
End If
ElseIf Me.tbApp1.Text.Trim = "" Then
ErrorProvider1.Clear()
End If
End Sub
Masked Textbox use
'Private Sub mtbApp1_TypeValidationCompleted(ByVal sender As Object, ByVal e As TypeValidationEventArgs) Handles mtbApp1.TypeValidationCompleted
If Not Me.mtbApp1.Text = String.Empty Then
If (Not e.IsValidInput) Then
ErrorProvider1.SetError(mtbApp1, "The data you supplied must be a valid date in the format mm/dd/yyyy.")
Else
' Now that the type has passed basic type validation, enforce more specific type rules.
Dim UserDate As DateTime = CDate(e.ReturnValue)
If (UserDate = DateTime.Now) Then
ErrorProvider1.SetError(mtbApp1, "The data you supplied must be today's date")
e.Cancel = True
End If
End If
ErrorProvider1.Clear()
End If
End Sub'
I noticed for a date like 03/18/2014 when it loaded back into the masked textbox it converts to 31/82/014. How could i fix this? The query pulls back the field as
CONVERT(VARCHAR(10),Date,101) AS Date
I set it in vb as :
Dim Approval1 As Date = Nothing
and then
If Not IsDBNull(((WorklistsDS.Tables(0).Rows(0).Item("Approval1")))) Then
Approval1 = ((WorklistsDS.Tables(0).Rows(0).Item("Approval1")))
End If
and then loaded into the masked textbox as:
If Approval1 <> Nothing Then
Me.mtbApp1.Text = Approval1
End If
You could also simplify your validation with
If IsDate(tbApp1.Text) Then
'valid date now just check if date falled within permitted range
Dim CompDate As Date = CDate(tbApp1.Text)
Dim MidDate As Date = *enter your min date here*
Dim MaxDate As Date = *enter your max date here*
If CompDate >= MinDate AndAlso CompDate <= MaxDate Then
'Date is within permitted range
......
Else
'Date outside range
'Display error
End If
Else
'text in tbApp1 is not a date
'Display Error
End If

Formatting Time (HH:MM:SS)

I'm taking values from Numeric Ups and Downs for Hours, Minutes and Seconds.
The problem is that, for example, if the time for example is 9.15 am it will show as 9:15:0
What I want to do is format them so if any of the values(Hours, Minutes or seconds) is less than 10, it will add a 0 before the number so as the number shows as 09:15:00.
What I tried is this but it does not work:
Sub BtnSetClick(sender As Object, e As EventArgs)
lbl8.Visible = True
Dim nmTime As String = nmHour.Value.ToString + nmMin.Value.ToString + nmSec.Value.ToString
lblST.Text.Format(nmTime.ToString, "HH:MM:SS")
lblST.Text = (nmTime)
lblST.Visible = True
End Sub
You seem to be doing it a bit backward by converting everything to string multiple times, try something like this:
Dim ts As new TimeSpan(CInt(nmHour.Value), CInt(nmMin.Value), CInt(nmSec.Value))
lblST.Text = ts.ToString("HH:MM:SS")
The documentation for TimeSpan.ToString is useful.
Edit: Updated the code to reflect Tim's comment about datatype.
Try this:
Sub BtnSetClick(ByVal sender As Object, ByVal e As EventArgs)
lbl8.Visible = True
Dim nmTime As String = nmHour.Value.ToString().PadLeft(2, '0') + nmMin.Value.ToString().PadLeft(2, '0') + nmSec.Value.ToString().PadLeft(2, '0')
lblST.Text = nmTime
lblST.Visible = True
End Sub
try using the TimeSpan object, it should do all the hard work for you!
Dim nmTime As New TimeSpan(nmHour.Value, nmMin.Value, nmSec.Value)
lblST.Text = nmTime.ToString
lblST.Visible = True

How can I compare two times in VB.net

I want to compare two times in VB.net:
I have 1:42:21 PM and I want it to compare with TimeOfDay in VB.net how can I do that?
New DateTime(1, 1, 1, 13, 42, 21) > TimeOfDay
Or you can enclose a DateTime expression in # signs:
TimeOfDay > #1:42:21 PM#
Show the time difference in hours, minutes and seconds
Dim TimeEnd As DateTime = #5:00:00 PM#
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim span As System.TimeSpan = TimeEnd.TimeOfDay - DateTime.Now.TimeOfDay
Label1.Text = span.Hours & "hr:" & span.Minutes & "min:" & span.Seconds & "sec"
End Sub
You'd work out the format of your input time, and then call the ToString() method on your vb.net object, putting the same format in.
So for example, if your input format is h:mm:ss tt as it appears to be in your case, one method would be to do:
Dim compareTime As String = "1:42:21 PM"
If compareTime = DateTime.Now.ToString("h:mm:ss tt") Then
' The times match
End If
If you want to do some kind of comparison, you should use the DateTime.Parse() function to convert your input date into a DateTime object. Then you can simply use the > or < signs:
Dim myCompareTime As DateTime = DateTime.Parse("1:42:21 PM")
If myCompareTime.TimeOfDay > DateTime.Now.TimeOfDay Then
' Compare date is in the future!
End If
The following sample function can be used to compare time
Function comTime()
Dim t1 As Integer = DateTime.Now.TimeOfDay.Milliseconds
Dim t2 As Integer = DateTime.Now.AddHours(1).Millisecond
If (t1 > t2) Then
MessageBox.Show("t1>t2")
ElseIf (t1 = t2) Then
MessageBox.Show("t1=t2")
Else
MessageBox.Show("t2>t1")
End If
End Function
is it something along the lines of this that you are looking for?
To compare the time portion of two DateTime values:
Dim TimeStart as DateTime = #1:42:21 PM#
Dim TimeEnd as DateTime = #2:00:00 PM#
If TimeStart.TimeOfDay < TimeEnd.TimeOfDay Then
Console.WriteLine("TimeStart is before TimeEnd")
End If
Dim MyDate As DateTime = Convert.ToDateTime(MyDateAsString)
Dim MyFractionOfDay As Double = MyDate.TimeOfDay.TotalDays
The question is still valid in 2022. After extracting time as a fraction of day, it can be compared, or used to visualize progress through the day.