Hey all i have a song playing that displays the time like so:
0:00 / 4:47
The first time is the tracks current time.
The second is the total track time of that song playing.
I split it like so:
Dim tmpTimes As Array = lblSongTime.Text.Split("/")
So tmpTimes(0) gives me 0:00 and tmpTimes(1) gives me 4:47.
Now i tried to subtract the tmpTimes(1) from tmpTimes(0)
Debug.Print(CDbl(tmpTimes(1).replace(":", "") - tmpTimes(0).replace(":", "")))
and i get: 447.. 446... 445... etc
What kind of calulation do i need in order to return a decending count?
Example: 4:47...4:46.....4:45...etc using the current time tmpTimes(0)?
You need to split the text MM:SS into Minutes and Seconds, then convert that to total seconds (m * 60 + s). Then you can do the math on seconds. Then you will need to convert it back into Minutes and Seconds for display.
You may also be able to use the Timespan class to do this.
Solved:
Dim times As String() = lblSongTime.Text.Split("/"c)
Dim elapsedTime As TimeSpan = TimeSpan.ParseExact(times(0).Trim(), "m\:ss", Nothing)
Dim totalTime As TimeSpan = TimeSpan.ParseExact(times(1).Trim(), "m\:ss", Nothing)
Dim remainingTime As TimeSpan = totalTime - elapsedTime
Debug.WriteLine(remainingTime.ToString("m\:ss"))
Related
How do I subtract Time in Excel VBA?
I tried to subtract these two values, but I'm getting this value "2.1527777777778E-02" instead. What does this mean?
Timein = 12/7/16 12:00:00 AM
Timeout = 12/7/16 12:30:00 AM
Here's a sample of my code. Thanks in advance.
Dim Total as Double
Dim Timein as Date
Dim Timeout as Date
Total = TimeValue(Timeout) - TimeValue(Timein)
'Result Total=2.1527777777778E-02
You can use the DateDiff Function to get the difference in year/days/seconds or whatever.
Here the example for minutes.
Dim Timein As Date
Dim Timeout As Date
Timein = "12/7/16 12:00:00 AM"
Timeout = "12/7/16 12:30:00 AM"
Debug.Print DateDiff("n", Timein, Timeout)
Output:
30
Interval Explanation
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second
What you have done is perfectly correct, as can be seen by the following code:
Sub test()
Dim Total As Double
Dim Timein As Date
Dim Timeout As Date
Timein = CDate(Range("A1").Value)
Timeout = CDate(Range("A2").Value)
Total = TimeValue(Timeout) - TimeValue(Timein)
Debug.Print Total
Debug.Print Format(Total, "hh:mm:ss")
Range("A3").NumberFormat = "hh:mm:ss"
Range("A3").Value = Total
Debug.Print "Number of hours = " & Total * 24
End Sub
As mentioned by vacip in a comment, Date/Time variables are stored in VBA in "days" so, for example, Now for me is the number 42867.7513310185.
2.1527777777778E-02 is using a method of displaying a value called Scientific Notation. In your case, it means 2.1527777777778 times 10 to the power of -2. Or you could think of the E-02 part as meaning shift the decimal point two places to the left (left because it's negative).
So: 0.021527777777778.
Excel treats time (both dates and times of day) as whole days so half a day (12 hours) would be represented as 0.5.
So the result itself represents the decimal fraction of an entire day, if you want this in minutes for example, you would multiply the value by 1440 (24hr x 60min make a day) which would give you 31mins.
In your example, you're finding the difference between 12:00 and 12:30 so you should actually be getting a result of 2.08333333333333E-02 which if multiplied by 1440 would give you 30mins.
Excel gives you tools to find the difference between two points in time though that take all that complex math(s) away - DateDiff and #holger has given you everything you need there to write your own code.
You have defined the total as double, which returns you number. you need to dim the total as date so that returns you a time.
Dim Total as Date
Dim Timein as Date
Dim Timeout as Date
Total = TimeValue(Timeout) - TimeValue(Timein)
I'm trying to get a quick ETA on some pre-determined values, 16 and 40. So for example, I need my code to quickly calculate an ETA on an item if it takes 16 hours, but only count the 9-5 (8) hours per day. Obviously I'd need to include the remaining hours of that day, which I have in the code snipped below. However I'm giving myself an ofly sore head trying to work out the best way to proceed with the code. Perhaps someone's got a good idea?
Dim TargetTime as Integer = 16
Dim currentHr As Integer = current.Hour
Dim TodaysRemainingHours As Integer = 0
If currentHr >= 9 AndAlso currentHr < 17 Then
'Count remaining hours
TodaysRemainingHours = (17- currentHr)
Else
'Dont count today
TodaysRemainingHours = 0
End If
My plan is:
TargetTime - TodaysRemainingHours --- Gives the value to count
to.
Somehow calculate the hours based on 9-5 time spans only.
Display lblOutput as: "ETA: 2pm 25/11/2016"
As you can see I know how to get the vaule I need to count to, but I need some help with firstly only counting the hours in each day from 9-5 and then returning the actual hour estimated. This isn't for anything profitable, it's a personal ETA program.
Thank you topshot, your comment helped me work it out! The below code seems to work for me, I haven't identified any issues anyway. I had to make sure I wasn't counting the remaining hours in the current day if the time is past 5pm as well. Thank you.
Dim TargetTime As Integer = 16
Dim current As Datetime = DateTime.now
Dim currentHr As Integer = current.Hour
Dim TodaysRemainingHours As Integer = 0
If currentHr >= 9 AndAlso currentHr < 17 Then
'Count remaining hours
TodaysRemainingHours = (17 - currentHr)
Else
'Dont count today
TodaysRemainingHours = 0
End If
If currentHr >= 9 AndAlso currentHr < 17 Then
'Deduct todays hours from target time.
TargetTime = (TargetTime - TodaysRemainingHours)
'Display results
MsgBox("ETA: " & Now.AddDays(TargetTime / 8))
Else
'Skip todays hours and count from tomorrow morning at 9am
Dim Tomorrow As DateTime = Today.AddDays(1)
Dim TomorrowMorning As TimeSpan = new TimeSpan(09, 00, 0)
Tomorrow = Tomorrow.Date + TomorrowMorning
'Display results
MsgBox("ETA: " & Tomorrow.AddDays(TargetTime / 8))
End If
How can I generate the time (in hours and minutes) from given rate (for payments)? The user will need to enter the payment and the rate to get the total time duration. How can this mission be accomplished?
example:
rate = $2.00 per hours
payment = $5.00
result:
duration = 02 h 30 minutes
Thank you.
Use TimeSpan to simplify your code...
Private Function GetDuration(hourlyRate as decimal, payment as decimal) As TimeSpan
return TimeSpan.FromHours(payment / hourlyRate)
End Function
' ...
Dim duration = GetDuration(2, 5)
Console.WriteLine("{0} hours {1} minutes", duration.Hours, duration.Minutes)
Fiddle: http://dotnetfiddle.net/2tvYMK
Once you have the decimal point representation of time in hours (ie. 2.5), all you have to do is:
take the integer part - that's the number of full hours;
subtract the integer part from total and multiply by 60; that's the number of minutes
Something along these lines should work:
Dim hours as Integer
Dim minutes as Integer
Dim time as Double
time = payment / rate
hours = CInt(time)
minutes = CInt((time - hours) * 60)
Console.WriteLine("duration = {0} h {1} minutes", hours, minutes)
hours = payment \ rate;
minutes = (payment/rate - hours) * 60;
Use a TimeSpan structure. It will do the calculations of hours and minutes for you.
Dim rate As Double = 2.0
Dim payment As Double = 5.0
Dim time = TimeSpan.FromHours(payment / rate)
Dim duration = [String].Format("{0:00} h {1:00} minutes", time.Hours, time.Minutes)
' ==> "02 h 30 minutes"
You can also use the Decimal type when working with money. It has the advantage of not introducing additional rounding errors when converting from and to binary formats. However, TimeSpan.FromHours expects the hours as Double. Therefore Double seems appropriate for this little example.
I need to subtract DateTimePicker1 - DateTimePicker2
DateTimePicker1 get infornet from The man who ran the software
DateTimePicker2 get infornet from The man who ran the software
The Datetimekiper is like (HH:mm d/M/y)
the date is because its can take 4 days.
so the hour can be 72- 96
I just need the numbers of hours and minutes.
You need to be handling the DateTime value, not the control itself.
try something like this:
Dim x = DateTimePicker1.value - DateTimePicker2.value
and then this x will have the timespan, so you can get total hours like this:
Dim hours = x.TotalHours
I want to add a label that prints the elapsed time like a normal clock (when seconds reachs "59" then add "1" min to the counter) but my time span add minutes when the seconds reaches the number "30"... what I'm doing wrong?
Dim ElapsedTime As TimeSpan
While log_button.Text = "Stop logger"
ElapsedTime = Now().Subtract(StartTime)
Label5.Text = String.Format("Minutos transcurridos: {0:00}:{1:00}", CInt(ElapsedTime.TotalMinutes) Mod 60, CInt(ElapsedTime.TotalSeconds) Mod 60)
Application.DoEvents()
End While
I get a wrong incrementation like this:
00:01
...
00:28
00:29
00:30
01:31
01:32
etc...
That's because you are rounding the floating point number that represents total minutes. When the numbers reaches 0.5 it will be rounded to 1.
Use the Floor method to truncate the number:
CInt(Math.Floor(ElapsedTime.TotalMinutes)) Mod 60
You can also use the Minutes property, that does all that:
ElapsedTime.Minutes