How to set 2 different time display in textbox - vb.net

I have 2 textbox in vb.net form.
In one textbox it displays system time.
In second textbox i want to display time that is 2 hrs later than system time.
How can i do that with timespan.

Does it have to be a timespan? You can do it with a Date variable.
Dim dt As Date = Date.Now
textbox1.Text = dt.ToString()
textbox2.Text = AddTimeZoneDiff(2, dt)
Private Function AddTimeZoneDiff(offset As Double, dt As Date) As String
Return dt.AddHours(offset).ToShortTimeString()
End Function

Related

Vb.net Multiplying textbox with time and combo box value

I have a masked textbox with time value ("hh:mm" the duration the task wil take) and a combo box with 1-10.
How do I mutilply the masked textbox with the combo box to get the total dutation it would take in "hh:mm.
I have txttime1 as the first textbox that holds the time. (masked textbox)
Cmb1 with 1-10, this indicates how many times the txttime1 must be multiplied.
Txtdura1 as the answer to the multiplication. Basically the total duration of the event.
Any direction would be great.
Convert the string from the textbox to a TimeSpan. Then change to TotalMinutes which is a Double so you can perform multiplication. Take the result of the multiplication and change it to a TimeSpan .FromMinutes. You can then format the result in various ways.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim ts As TimeSpan = TimeSpan.ParseExact(TextBox2.Text, "h\:m", CultureInfo.CurrentCulture)
Dim dblTotalMinutes As Double = ts.TotalMinutes
Dim Multiplier As Integer = CInt(ComboBox1.SelectedItem)
Dim MultipliedMinutes As Double = dblTotalMinutes * Multiplier
Dim MultipliedTimeSpan As TimeSpan = TimeSpan.FromMinutes(MultipliedMinutes)
'For days:hours:minutes
TextBox3.Text = MultipliedTimeSpan.ToString("d\:hh\:mm")
'Total Hours as double
TextBox4.Text = MultipliedTimeSpan.TotalHours.ToString
End Sub
Split the hours and minutes apart from each other, create a TimeSpan object and multiply that by the factor from the ComboBox:
Dim duration As TimeSpan = TimeSpan.Parse(txttime1.Text)
Txtdura1 = duration.Multiply(Integer.Parse(Cmb1.Text)).ToString("hh\:mm")
Relevant documentation:
TimeSpan.Parse()
TimeSpan.Multiply()
TimeSpan.ToString()

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)

How to add 1 month to selected DateTimePicker

I'm having an issue with DateTimePicker.
What I am currently trying to do is based off of what text is in lblPrevSem(Previous Semester), which is getting its selection from a drop down on a previous screen, i want to add a certain amount of time to the DateTimePicker.
Public Property CustomFormat As String
Dim SemesterMonths As Integer
Dim SemesterDays As Integer
Private Sub DeptCreatePrevSch_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim SemesterYear() As String = DeptPrevSch.CboSem.Text.Split(",")
lblPrevSem.Text = SemesterYear(0)
cboYear.Text = Date.Now.Year
For i As Integer = 0 To 5
cboYear.Items.Add(Date.Now.Year + i)
cboYear.SelectedIndex = 0
Next
If InStr(lblPrevSem.Text, "Fall") Then
SemesterMonths = 1
ElseIf InStr(lblPrevSem.Text, "Spring") Then
SemesterMonths = 1
ElseIf InStr(lblPrevSem.Text, "Summer") Then
SemesterDays = 14
End If
Call dtpStart_ValueChanged(sender, e)
End Sub
Private Sub dtpStart_ValueChanged(sender As Object, e As EventArgs) Handles dtpStart.ValueChanged
Dim StartDate As Date
Dim StartStringDate As String
Dim EndDate As Date
Dim EndStringDate As String
dtpStart.Format = DateTimePickerFormat.Custom
dtpStart.CustomFormat = "MMMM dd, yyyy dddd"
StartDate = dtpStart.Value.ToString
StartStringDate = StartDate.ToString("MMMM dd, yyyy dddd")
lblRegStartDate.Text = StartStringDate
EndDate = dtpStart.Value.AddMonths(SemesterMonths)
EndDate = dtpStart.Value.AddDays(SemesterDays)
EndStringDate = EndDate.ToString("MMMM dd, yyyy dddd")
lblRegEndDate.Text = EndStringDate
End Sub
I can get it to add in days just fine but when ever i try and add in 1 month, it doesn't seem to work at all.
I've tried multiple different ways to add in a 1 month but nothing so far has worked. The closet ive been was adding in 30 days but then that doesn't account for months that have 31 days.
Reg Start Date is what ever the DateTimePicker is and Reg End Date should be the added days based off of what lblPrevSem is
Both Reg Start/End Date are displayed as labels
(i.e. Fall = 1 Month, Spring = 1 Month, Summer = 2 Weeks)
Your problem is that you are resetting the value for EndDate after adding the SemesterMonths value. You should add the SemesterDays value to the EndDate variable, not reset the value of EndDate with dtpStart.Value.AddDays(SemesterDays):
EndDate = dtpStart.Value.AddMonths(SemesterMonths)
EndDate = EndDate.AddDays(SemesterDays)
Just get the datetimepicker value and put .AddYears(0) or .AddDays(0) or AddMonths(0) behind it.
But you can also use them all at the same time.
nextServiceDateTimePicker.Value.AddYears(0).AddDays(0).AddMonths(0);
Just replace the 0 with lets say i and give it the value you need it to be.

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

add computed remainingTime to each inserted row of a datagridview

Hello on my project I am using vb and I have a datagridview binding with datasource.
For example I have this columns name
StartTime- this show the time a job started
7:00 am
4:30 pm
Hours- how long that job is going to run
30 minutes
2 HOURS
I want to be able to add the compute remaining time to each row that is inserted into the datagridview.
I already have a column name remainingTime that is not binding to the datasource. How can i add the compute remainingtime to each row. Even when the user inserted a new row? I already calculate the remainingTime but it only do this for the first row.
In my Form Load I have
Dim myTime As Date
'RemainingTime
Dim totalTime As Date = runningJobs_list.Rows(0).Cells(5).Value
' Dim totalTime As Date = runningJobs_list.Rows(0).Cells(5).Value
myTime = totalTime.AddHours(runningJobs_list.Rows(0).Cells(6).Value)
' myTime = totalTime.AddHours(runningJobs_list.Rows(0).Cells(6).Value)
Timer.Start()
this is my timer to do the countdown of reaming time
Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer.Tick
'variable to compare two timespan
Dim myspan As TimeSpan
myspan = TimeSpan.Zero
'decrease myTime to actual system time
Dim remainingTime As TimeSpan = myTime.Subtract(Date.Now)
'if the remaining time is less than zero then set red the entire row otherwise decrease timer
If remainingTime < myspan Then
runningJobs_list.Rows(0).DefaultCellStyle.BackColor = Color.Red
Else
runningJobs_list.Rows(0).Cells(8).Value = remainingTime
End If
End Sub
Please could someone help me?
You have to wrap that calculation into foreach loop which loops through all rows in grid (except last empty row. Check for rows IsNewRow status, or if Cells(0).Text is empty to validate is it empty or not...)
So this:
runningJobs_list.Rows(0).Cells(8).Value = ...
Should be something like this:
ForEach gridRow As DataGridRow in runningJobs_List.Rows
gridRow.Cells(8).Value = ...<br />
Next