im trying to find the gap between 2 numbers - vb.net

I'm having trouble finding the gap between 2 numbers for a parking charge. I tried this:
'time for entry
Dim entered As String = txtHourEnter.Text + ":" + txtMinEnter.Text
Dim time As DateTime
Dim display As String = "Invalid entry"
If DateTime.TryParse(entered, time) Then
display = time.ToString("h:mm tt")
End If
lblTimeIn.Text = display
'time for exited
Dim exited As String = txtHourExit.Text + ":" + txtMinExit.Text
Dim out As DateTime
Dim display2 As String = "invalid entry"
If DateTime.TryParse(exited, out) Then
display2 = out.ToString("h:mm tt")
End If
lblTimeOut.Text = display2
'parking time
Dim parkingtime As String = (display - display2)
lblParkingTime.Text = parkingtime
But I get this error:
The OP forgot to include the error message. How embarrassing for them :(

The code was trying to subtract the strings, instead of the timestamps. You need to get actual datetime values and subtract those.
Dim hourEnter As Integer = Int32.Parse(txtHourEnter.Text)
Dim minuteEnter As Integer = Int32.Parse(txtMinEnter.Text)
Dim hourExit As Integer = Int32.Parse(txtHourExit.Text)
Dim minuteExit As Integer = Int32.Parse(txtMinExit.Text)
Dim timeEnter As DateTime = DateTime.Today.AddHours(hourEnter).AddMinutes(minuteEnter)
Dim timeExit As DateTime = DateTime.Today.AddHours(hourExit).AddMinutes(minuteExit)
Dim parkingTime As TimeSpan = timeExit - timeEnter
lblTimeIn.Text = timeEnter.ToString("h:mm tt")
lblTimeOut.Text = timeExit.ToString("h:mm tt")
lblParkingTime.Text = parkingTime.ToString("h:mm")

Related

How to add duration between two times to listview in vb .NET

I have a ListView that I want to get the duration between the two times and add in the fifth column for each row.
I have no any idea how i can do this.
If you can help me, so show me with code please.
Like this:
I tried with this code, but it's not work:
For Each it As ListViewItem In ListView1.Items
Dim dFrom As DateTime
Dim dTo As DateTime
Dim sDateFrom As String = it.SubItems(1).Text
Dim sDateTo As String = it.SubItems(2).Text
If DateTime.TryParse(sDateFrom, dFrom) AndAlso DateTime.TryParse(sDateTo, dTo) Then
Dim TS As TimeSpan = dTo - dFrom
Dim hour As Integer = TS.Hours
Dim mins As Integer = TS.Minutes
Dim secs As Integer = TS.Seconds
Dim msec As Integer = TS.Milliseconds
Dim timeDiff As String = ((hour.ToString("00") & ":") + mins.ToString("00") & ":") + secs.ToString("00") + "." + msec.ToString("000")
it.SubItems.Add(timeDiff)
End If
Use the same loop where you populate the control to calculate and add the duration subitem. You don't need to do that in a separate loop. Convert the StartDate & EndDate strings to DateTime or TimeSpan objects, subtract the end time from the start time to get a TimeSpan object with the duration, call the ToString method and pass the "s\.fff" format to set the value of the duration's subitem.
Example
Imports System.Globalization
Dim inFormat = "hh\:mm\:ss\,fff"
Dim outFormat = "s\.fff"
Dim provider = CultureInfo.InvariantCulture
For Each lvi As ListViewItem In listView1.Items
Dim tsStart As TimeSpan, tsEnd As TimeSpan
If TimeSpan.TryParseExact(lvi.SubItems(1).Text, inFormat, provider, tsStart) AndAlso
TimeSpan.TryParseExact(lvi.SubItems(2).Text, inFormat, provider, tsEnd) Then
lvi.SubItems.Add((tsEnd - tsStart).ToString(outFormat))
End If
Next
In case and in somehow you already have the duration subitem in the collection, set it's .Text property instead of calling the .Add(...) method.
lvi.SubItems(4).Text = (tsEnd - tsStart).ToString(outFormat)
Again, you don't need a separate loop, in the main loop where you add the other subitems, replace the lvi.SubItems(1).Text and lvi.SubItems(2).Text parameters in the preceding example with their sources. Their properties in a model or their variables if you don't have a model.
I don't know your code
I think you can do it by using the source below.
Dim dFrom As DateTime
Dim dTo As DateTime
Dim sDateFrom As String = "00:00:06.200"
Dim sDateTo As String = "00:00:07.680"
If DateTime.TryParse(sDateFrom, dFrom) AndAlso DateTime.TryParse(sDateTo, dTo) Then
Dim TS As TimeSpan = dTo - dFrom
Dim hour As Integer = TS.Hours
Dim mins As Integer = TS.Minutes
Dim secs As Integer = TS.Seconds
Dim msec As Integer = TS.Milliseconds
Dim timeDiff As String = ((hour.ToString("00") & ":") + mins.ToString("00") & ":") + secs.ToString("00") + "." + msec.ToString("000")
MsgBox(timeDiff) 'output
End If
Be sure you have a column ready to receive the new SubItem.
I proceeded with the comma that I asked about in comments. You can changed the .ParseExact if it is really a period.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With ListView1.Columns
.Add("Start Time")
.Add("End Time")
.Add("Duration")
End With
Dim li As New ListViewItem("00:00:06,200")
li.SubItems.Add("00:00:07,680")
ListView1.Items.Add(li)
End Sub
Even though the first column is the ListViewItem is the Text property, it is also SubItems(0). This can be confusing. You do have your indexes correct.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
For Each li As ListViewItem In ListView1.Items
Dim sDateFrom As String = li.SubItems(0).Text 'also works with il.Text
Dim sDateTo As String = li.SubItems(1).Text
Dim FormatString = "hh:mm:ss,fff"
Dim provider = CultureInfo.InvariantCulture
Dim StartTime = Date.ParseExact(sDateFrom, FormatString, provider)
Dim EndTime = Date.ParseExact(sDateTo, FormatString, provider)
Dim TS As TimeSpan = EndTime - StartTime
'Dim timeDiff As String = $"{TS.Hours:00}:{TS.Minutes:00}:{TS.Seconds:00}.{TS.Milliseconds:000}"
'or
Dim timeDiff = TS.ToString("c")
li.SubItems.Add(timeDiff)
Next
End Sub
When you have a string with several variables that need to be inserted use an interpolated string which is preceded by a $. This allows you to insert your variables directly in line enclosed in { }. This is much easier to write, read, and understand. You also avoid many mistakes with quotes and concatenation characters. Formatting of the variables is accomplished by the format following a colon inside the braces. If you can stand a few extra zeros, you can format the TimeSpan directly with .ToString("c").

How to get and subtract the minute in datetimepicker to show on the textbox? (im using vb.net)

When i'm trying to compute time in my datetimepicker for example 12:00 AM - 3:40 AM the result is showing 3:-40.
Please help!
Dim HoursDiff = DateDiff(DateInterval.Hour, DTPTS.Value, DTPTE.Value)
Dim minutesDiff = DateDiff(DateInterval.Minute, DTPTS.Value, DTPTE.Value)
Dim totalMin As Integer = minutesDiff Mod 60
Dim Total As String = HoursDiff & ":" & totalMin
total.Text = Total
Dim totalmin2 As Integer = totalMin2 - txtboxMM.Text
Dim totalhours As Integer = HoursDiff - TxtboxHH.Text
Dim total2 As String = totalhours & ":" & totalmin2
TxtboxTRTint.Text = total2`
The easiest and most convenient way to subtract total minutes is by using TimeSpan.FromMinutes() which picks TotalMinutes property from DateTime.Subtract() like this:
Dim TotalMin = TimeSpan.FromMinutes((DTPTE.Value.Subtract(DTPTS.Value)).TotalMinutes)
TxtboxTRTint.Text = String.Format("{0}:{1:00}", TotalMin.Hours, TotalMin.Minutes)
The result now should be 3:40.
Example demo: .NET Fiddle

vb.net date of the day after every 24 hours

I have a timer which is to tick after every 86400000seconds (every 24 hours and therefore every day) to put the new day in a DateTimePicker, dtPicker1. Unfortunately, after the timer ticks the result brings the time of the day in addition to the date (for example 2017-03-18 00:00:05, instead of 2017-03-18. When I use the messagebox to check the output, I get the date without the time but the next day (after the timer ticks, it adds the time and therefore the code fails.
`'ticks every 86400000 miliseconds (a day)
dtPicker1.Enabled = True
dtPicker1.Text = ""
Dim mFmt As String = "yyyy-MM-dd"
dtPicker1.Format = DateTimePickerFormat.Custom
dtPicker1.CustomFormat = mFmt
dtPicker1.Text = ""
Dim st As Date = Today.AddDays(-1).ToShortDateString
Dim cf As String = Today.AddDays(-1)
Dim dr As String = cf.Substring(3, 2)
'MsgBox(dr)
Dim de As String = cf.Substring(6, 4)
Dim fg As String = cf.Substring(3, 2)
Dim ab As String = cf.Substring(0, 2)
'MsgBox(de & "-" & fg & "-" & ab, vbInformation, "Here you Go")
dtPicker1.Value = de & "-" & fg & "-" & ab`
Help will be greatly appreciated.
You don't need to use substrings, you can set the value directly as a date.
dtPicker1.Text = ""
Dim mFmt As String = "yyyy-MM-dd"
dtPicker1.Format = DateTimePickerFormat.Custom
dtPicker1.CustomFormat = mFmt
dtPicker1.Value = Today.AddDays(-1)

Countdown timer in vb.net

I'm having a start time as 11:30:25PM and an end time as 11:45:25AM
So now I would like to get the diff between the end time and the start time
This is what I have used the below code and working pretty well:
Dim dFrom As DateTime
Dim dTo As DateTime
Dim sDateFrom As String = Now.ToString("h:mm:ss tt")
Dim sDateTo As String = txtlogout1.Text
If DateTime.TryParse(sDateFrom, dFrom) AndAlso DateTime.TryParse(sDateTo, dTo) Then
Timer1.Start()
Dim TS As TimeSpan = dTo - dFrom
Dim hour As Integer = TS.Hours
Dim mins As Integer = TS.Minutes
Dim secs As Integer = TS.Seconds
Dim timeDiff As String = ((hour.ToString("00") & ":") + mins.ToString("00") & ":") + secs.ToString("00")
txtremaining1.Text = timeDiff
End If
Now the problem is if the start time is 11:30:25PM and the end time is 12:00:25AM then the remaining time is showing as -23:30:00
So what's the correct way of handling this?
Are you only concerned about spanning one day? Could you just check whether your Timespan variable is negative, and add a day if it is?
If TS.TotalMilliseconds < 0 Then TS = TS.Add(TimeSpan.FromDays(1))
If DateTime.TryParse(txtlogout1.text, dTo) Then
Dim ts as Timespan = dTo.Subtract(DateTime.now)
If ts.TotalMilliseconds < 0 Then ts = ts.Add(TimeSpan.FromDays(1))
txtremaining1.Text = ts.ToString()
End If

How to set AccountExpires in VB.NET via a AD DirectoryEntry

I needed to set the accountExpires property in the AD DirectoryEntry couldn't find a simple answer.
Found some information;
http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal.aspx
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/182bfb6a-8b23-4c96-9379-101a4d91241a
http://www.rlmueller.net/AccountExpires.htm
Saw some articles re ADS****.dll but didn't think I needed to use this method
Dim valueToSet As Date = Now.AddDays(10)
Dim ADSPath As String = "LDAP://cn=..."
Dim de As DirectoryEntry = New DirectoryEntry(ADSPath)
Dim d As TimeSpan = valueToSet.ToUniversalTime - Date.Parse("01/01/1601")
Dim ValueToSetAsString As String = d.Ticks.ToString
' it appears that the ticks value is too large for the value of the directory entry
' converting to a string (18 chars or so) works!
de.Properties("accountexpires").Value = ValueToSetAsString
Thanks to Brian it looks like the large amount of code wrote above can be simplified;
de.Properties("accountexpires").Value = valueToSet.ToFileTime.ToString
A function to return the AccountExpires and other largeInteger issues in VB.NET
Function ConvertADValueToDateTime(ByVal li As Object) As DateTime
' http://bytes.com/topic/visual-basic-net/answers/512901-lastlogontimestamp
Try
Dim lngHigh = li.HighPart
Dim lngLow = li.LowPart
Dim lastLogon = (lngHigh * 2 ^ 32) - lngLow
Dim returnDateTime As DateTime = DateTime.FromFileTime(lastLogon)
Return returnDateTime
Catch ex As Exception
Return Nothing
End Try
End Function
Example use :
Dim d As DateTime = ConvertADValueToDateTime(de.Properties("accountexpires").value)
If d = "01/01/1601" Then
' no expiry date
Return Nothing
Else
Return d
End If
An alternative method
Convert LDAP AccountExpires to DateTime in C#
Something like this will set your account to expire in 30 days:
Dim de As New DirectoryEntry("LDAP://cn=foo,cn=users,dc=contoso,dc=com")
de.Properties["accountExpires"].Value = DateTime.UtcNow.AddDays(30).ToFileTime()
de.CommitChanges()
This uses a DateTimePicker on a form but it should be trivial to use any other date format..
Imports System.DirectoryServices
Imports System.DirectoryServices.ActiveDirectory
Imports System.IO
'Get the user
Dim EntryString As String
EntryString = "LDAP://...."
Dim dirEntry As DirectoryEntry
dirEntry = New DirectoryEntry(EntryString)
Dim dirSearcher As New DirectorySearcher(dirEntry)
dirSearcher.Filter = "(&(objectCategory=Person)(objectClass=user)(SAMAccountName=" & Trim(Form1.AccountNameTB.Text) & "))"
dirSearcher.SearchScope = SearchScope.Subtree
Dim searchResults As SearchResult = dirSearcher.FindOne()
'Set the date
Dim d1 As Date = Form1.AccountExpiresDTP.Value
Dim d2 As New DateTime(d1.Year, d1.Month, d1.Day)
d2 = d2.AddDays(1) 'Add one day so that it matches what is in AD
Dim ft As Long = d2.ToFileTime()
dirEntryResults.Properties("accountExpires").Value = ft.ToString 'You do need to turn it into a string
dirEntryResults.CommitChanges()
dirEntryResults.Close()