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
Related
I ran some code in VBA as per https://www.thespreadsheetguru.com/the-code-vault/2015/1/28/vba-calculate-macro-run-time and had a return of a negative value:
-20439 seconds
Does anyone know why? It actually ran for ~ 18hrs (1500 - 0900 next day)
Option Explicit
Sub CalculateRunTime_Minutes()
'PURPOSE: Determine how many minutes it took for code to completely run
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
Dim StartTime As Double
Dim MinutesElapsed As String
'Remember time when macro starts
StartTime = Timer
'*****************************
'Insert Your Code Here...
'*****************************
'Determine how many seconds code took to run
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
'Notify user in seconds
MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation
End Sub
The code uses Timer.
The Timer returns a Single representing the number of seconds elapsed since midnight. SyntaxTimerRemarks In Microsoft Windows the Timer function returns fractional portions of a second. On the Macintosh, timer resolution is one second. MSDN
Thus, if you start running at 15:00, the code would return something meaningful, if you end up to 23:59. If you end the next day at 09:00, it would return negative value.
You can rebuild the code, in order to get the date in account as well. Use Now, which returns the date and the time - 21.02.2018 10:33:55
This looks like a good possible alternative:
Sub WorkstAtMidnight()
Dim StartTime As Date
StartTime = Now()
'Do something incredible
MsgBox Round((Now() - StartTime) * 24 * 60 * 60, 0)
'24 hours times 60 minutes times 60 seconds (usually I just do 24*3600)
End Sub
Another alternative:
MinutesElapsed = Format((Timer - StartTime) / 86400 + IIf(Timer < StartTime, 1, 0), "hh:mm:ss")
This keeps track of the hours and minutes accurately up to a whole day (i.e. it resets at 24 hours of runtime). After which the real question is why does your code take so long!
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)
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.
How can I realize everyday local notifications in my app? So at first run I need to register first local notification at 14:00 and then everyday at 14:00 notification should appear.
User can change this time in app's settings.
How to do this mechanism?
You need to handle the notifcations on your end, but to make a timer that countsdown to a certain time every day, you would need to do something like this:
local targetDate = os.time{ year=2014, month=11, day=8, hour=0, sec=0 } -- Get the date that you want to count down to, in seconds
local text = false
local function enterFrame(event)
if text then text:removeSelf() end -- Everyframe, remove the old text object
local timeRemaining = (targetDate-os.time()) -- Take the difference between the target time and the current time
local days = timeRemaining / 86400 -- get the number of days left by dividing the remaining seconds by the number of seconds in a day
local hours = days%1 * 24 -- get the number of hours left by multiplying the remainder by the number hours in a day
local minutes = hours%1 * 60 -- get the number of minutes by multiplying the remainder by the number of minutes in an hour
local seconds = math.floor( minutes%1 * 60 + 0.5) -- multiply the remainder one more time by the number of seconds in a minute, and round to the nearest second.
-- make a new text object to display all the info
text = display.newText( "Will be available in "..math.floor(days).." days "..math.floor(hours).." hrs "..math.floor(minutes).." mins "..seconds.." secs ", 25, 140)
end
Runtime:addEventListener( "enterFrame", enterFrame )
You can repurpose your code to work with your project, but you need to use OS time and do certain calculations to each variable in order to get the time. Good luck.
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"))