Converting DateTime to an integer - vb.net

How would you convert a randomly generated time into an integer, This is how I have formatted my time;
StartTime = FormatDateTime(Now, DateFormat.LongTime)
EndTime = FormatDateTime(Now, DateFormat.LongTime)
Diff = (EndTime - StartTime.Subtract(TimeSpan))
So for example Diff = "08:30:12"
I want to be able to convert that to "8.30" as in 8 hours and 30 minutes.

8.30 is not an Integer.
However, you can use the TimeSpan.Hours and TimeSpan.Minutes properties with String.Format if you want a string with the hours and the minutes parts:
String.Format("{0}.{1}", Diff.Hours, Diff.Minutes)
Demo

You say you want an integer representation of your Diff result.
Supposing that Diff is a TimeSpan structure, why not use simply?
Dim x as Integer
x = Convert.ToInt32(Diff.TotalMinutes)
Of course I assume that the difference is never so big to overflow the integer

You can do :
Dim d As Decimal
d = Diff.Hours + Diff.Minutes / 100D
100D gives a decimal that is needed for the division. Integer division 30/100 gives 0

You could use the DateTime.DiffDate function, which returns a long
dim date1 as DateTime = Now
dim date2 as DateTime = Now.AddSeconds(-30600) ' 8.5 hours ago
dim lHr as long = DateDiff(DateInterval.Hour, date1, date2) '=-8
dim lMn as long = DateDiff(DateInterval.Minute, date1, date2) '=-510
lHr = DateDiff(DateInterval.Hour, date2, date1) ' = +8
lMn = DateDiff(DateInterval.Minute, date2, date1) ' = +510
(there are other intervals, days, seconds etc. in DateDiff which would also come in handy) Note that there is no rounding up of your values. Makes number of minutes within hour easy
num_Minutes_Past_Hour = lMn - lHr * 60 ' = 30

Related

VBA: How to make an IF statement on a DateDiff function

In a VBA project i'm working on, I need to count the number of lines where the difference between two dates is inferior to X hours.
My idea was to go through all the lines and check for each line, like this:
Dim count as Integer
if DateDiff("h", date1, date2) < 24 then
count = count + 1
End If
The problem is that I get an incompatibility type error (execution error 13).
Is it possible to make IF statements on a DateDiff function? Or is it maybe possible to make a filter with DateDiff as the condition?
Thanks for the help and sorry for my poor english as it's not my main language!
I have tested it like this without any errors.
Dim date1 As Date
Dim date2 As Date
date1 = "14/10/2015 19:00:00"
date2 = "14/10/2015 16:28:43"
If DateDiff("h", date1, date2) < 24 Then
count = count + 1
End If
The VBA conversion function CDate can apply a little of the overhead you constantly pay for to correct the dates. With that said, it is best to correct the data to begin with and not rely upon error controlled conversion functions.
Dim date1 As Date, date2 As Date, n As Long
date1 = CDate("14/10/2015 19:00:00")
date2 = CDate("14/10/2015 16:28:43")
Debug.Print date1 & " to " & date2
If IsDate(date1) And IsDate(date2) Then
If DateDiff("h", date1, date2) < 24 Then
n = n + 1
End If
'alternate
If date2 - date1 < 1 Then
n = n + 1
End If
End If
Given that 24 hours is a day and a day is 1, simple subtraction should be sufficient for this base comparison.
Your DMY format may cause problems with the EN-US-centric VBA in date conversion. If an ambiguous date string is found (e.g. "11/10/2015 16:28:43") you may find that you are interpreting it as MDY.

Comparing Time And Date with this format HH.MM mm/dd/yyyy.

Is it possible to compare using The format of military time and Date like this HH.MM mm/dd/yyyy.
For Example:
1
08.25 06/10/2014 > 23.18 06/09/2014
Result is True because the day 10 is greater than day 09
2
23.25 06/10/2014 > 23.30 06/10/2014
Result is false because the mins 30 is greater than mins 25
3
24.25 06/10/2014 > 1.30 06/10/2014
Result is true because the hrs 24 is greater than hrs 1
The Priority is Year -> Month -> Day -> Hours -> mins.
Seems like you are allowed to have non-standard time like 24.25.
Then you can use the following strategy - extract date, add time, compare.
Public Shared Function ToDateTime(ByVal value As String) As DateTime
Dim m As Match = Regex.Match(value, "^(?<hours>\d{1,2})\.(?<minutes>\d{2}) (?<date>\d{2}/\d{2}/\d{4})$")
If Not m.Success Then
Throw New ArgumentException("value")
End If
Dim dateOnly As DateTime = DateTime.ParseExact(m.Groups.Item("date").Value, "dd\/MM\/yyyy", CultureInfo.InvariantCulture)
Dim hours As Integer = Integer.Parse(m.Groups.Item("hours").Value)
Dim minutes As Integer = Integer.Parse(m.Groups.Item("minutes").Value)
Return dateOnly.AddHours(hours).AddMinutes(minutes)
End Function
Usage:
Console.WriteLine(ToDateTime("08.25 06/10/2014") > ToDateTime("23.18 06/09/2014"))
Console.WriteLine(ToDateTime("23.25 06/10/2014") > ToDateTime("23.30 06/10/2014"))
Console.WriteLine(ToDateTime("24.25 06/10/2014") > ToDateTime("1.30 06/10/2014"))

How to calculate positive difference between time from two DateTimes

I am having two date time picker start time and end time.I have to calculate difference between time from this end time and start time.And also how to check am or pm for calculating time difference.
I have tried this by using timespan. It gives me right answer,but when I select time suppose as 12:58:02 in end time and 10:57:05 in start time, it gives me wrong answer like -599. I want to know how to convert this negative difference to positive.
I have tried with the following code:
Dim startTime As Date
Dim endTime As Date
startTime = Convert.ToDateTime(dtpOpStTime.Value)
endTime = Convert.ToDateTime(dtpOpETime.Value)
Dim diff As System.TimeSpan
diff = endTime - startTime
actualTime = Convert.ToString(Int32.Parse(diff.Hours.ToString()) * 60 + Int32.Parse(diff.Minutes.ToString()))
ucTime.TxtCode.Text = actualTime
my another issue is as follows:
I am having 4 date time picker,2 for showing start date and end date and 2 for start time and end time.so when i changed date timespan getting is wrong .so how to resolve this.
I have tey with the following code:
Dim span As TimeSpan = dtpOpEDate.Value - dtpOpStdate.Value
Dim span1 As TimeSpan = dtpOpETime.Value - dtpOpStTime.Value
Dim duration As TimeSpan = span.Duration()
Dim duration1 As TimeSpan = span1.Duration()
Dim durDay As Int32 = duration.Days
Dim durHr As Int32 = duration1.Hours
Dim durMin As Int32 = duration1.Minutes
Dim totalDur = durDay * 24 * 60 + durHr * 60 + durMin
actualTime = totalDur.ToString()
ucTime.TxtCode.Text = actualTime
Problem is through this I am getting wrong time difference ,when i change suppose start time 10:51:02 PM and end time to 3:51:04 AM and start date to 25-Mar-2014 and End date to 26-Mar-2014 then difference should be 5 hours though the day change but i am getting wrong difference
A difference between two DateTimes returns a TimeSpan object. You can either use the Subtract method of DateTime or even use -. You have to use the subtract the earlier date from the later date:
Dim span As TimeSpan = dtpEnd.Value - dtpStart.Value
You can use the Duration method to get an absolute timespan, then the order doesn't matter:
Dim duration As TimeSpan = (dtpStart.Value - dtpEnd.Value).Duration()
If you for example want the number of minutes between, use the TotalMinutes property:
Dim minutes As Int32 = CInt(duration.TotalMinutes)

how to compare time in vba

I want to write a macro that compares two times that is available in cells A1 and B1
I tried to use the following code BUT it gave me "type dismatch" at date1 = TimeValue(Range("A1"))
for example, the value at cell A1 like this 11/18/2011 10:11:36 PM
dim date1 as date
dim date2 as date
date1 = TimeValue(Range("A1"))
date1 = TimeValue(Range("B1"))
if date1 > date2 then
'do something
else
'do something else
end if
you need to use Range("A1").Value
Two things:
try changing the value in A1 to 11/10/2011 10:11:36 PM If things
now work you may have a Regional Settings mismatch
you've declared date1 and date2 but are assigning twice to date1 and never
assigning to date2
use application.worksheetfunction.mod( date value, 1 )
You ought to understand that date and time in excel is represented by a serial number, in which 1 equals to a day, and time is repredented by decimals or fractions.
All systems base their date from day zero which us January 1, 1900 = 1, and January 2, 1900 = 2 and so on.
On the excel worksheet you cab retrieve the current date snd time using today(). On vba you use Now instead. Todays date, in "0" or "General" number formatting should show a number that starts with 42..., which represents the number of days since January 1, 1900.
Since there are 24 hours within a day, if you wish to refer to 1 hour or 1:00 AM the fraction or decimal in the serial number is equalent to 1/24. 7:00 PM = 19/24
mod() is a formula or function that will return the remainder of a division. Remember that time is represented by decimals, you do not need the actual whole numbers.
You can use the mod() formula in vba by using "application.worksheetfunction." before any.
When you divide a date and time with 1 using mod() it will return the remainder which is the decimal portion of your date aka the time.
Comparing datevalue("1:00 PM") will not equal CDate("May 8, 2015 1:00 PM")
sub compare_dates()
dim date1 as date
dim date2 as date
dim str as string
str = activesheet.range("A1").value 'str = "11/18/2011 10:11:36 PM"
str = Left(str,Instr(str," ")-1) ' str = "11/18/2011"
date1 = str ' assign it to date1
str = activesheet.range("B1").value ' in the same way b1 cell value
str = left(str,instr(str," ")-1)
date2 = str
if date1 > date2 then
' do something
end if
end sub
Can't it be done by simply using .Text instead of .Value?
Dim date1 As Date
Dim date2 As Date
Dim date3 As Date
date1 = TimeValue(Range("A1").Text)
date2 = TimeValue(Range("B1").Text)
date3 = TimeValue(Range("C1").Text)
If date3 >= date1 And date3 <= date2 Then
'Yes!
Else
'No!
End If

Datediff() function not getting the expected result in VB.NET

I am using the following code in my project. I want to find the number of days by given the last date and now.
Dim BorrowDate As Date
Dim i As Integer
BorrowDate = Date.Parse(txtBorrowDate.Text)
i = DateDiff(DateInterval.Day, BorrowDate, DateTime.Now)
for example, when BorrowDate is "01/Jul/2011" then the result is 7 days which it should be 10 to now. Please help
Since you are using .Net you might try this
Dim BorrowDate As Date = Date.Parse(txtBorrowDate.Text)
Debug.WriteLine(BorrowDate.ToString)
Debug.WriteLine(DateTime.Now.ToString)
Dim ts As TimeSpan = DateTime.Now - BorrowDate
Dim numdays As Integer = CInt(ts.TotalDays)
Debug.WriteLine(numdays.ToString("n0"))
edit: Init the variables and show the dates.