int seconds = 8;
String s = 'Remaining time: $seconds s';
print(s);
Output:
Remaining time 8 s
What is the best way to add a leading zero to get as output:
Remaining time 08 s
Of course, if seconds is > 10, I don't want a leading zero.
You can use the .padLeft() function on the string:
var seconds = 8;
print('${seconds.toString().padLeft(2, '0')}'); //Print: 08
Related
I'm having this problem for a while and I can't find a good way to resolve it. So I have a timestamp like this for example : local t = "00:00:0.031" and I'm trying to convert it into an array like this :
local ft = {
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 31
}
This is pretty much the same no matter the language so if you have an idea on how to solve this but don't know Lua you can submit your answer anyway in any language. I tried solving it myself using regex and I'm quite sure it's possible this way...
Thank you for the interest to my question, have a good day (:
You could use string.match to extract the substrings in a first place. In a second time, you could use the function tonumber to convert it into numbers.
function ParseTimestampString (TimestampString)
local Hours, Minutes, Seconds, Milliseconds = string.match(TimestampString, "(%d+)%:(%d+)%:(%d+)%.(%d+)")
local Result
if Hours and Minutes and Seconds and Milliseconds then
Result = {
hours = tonumber(Hours),
minutes = tonumber(Minutes),
seconds = tonumber(Seconds),
milliseconds = tonumber(Milliseconds)
}
end
return Result
end
With the following code, you could get the results you want:
Result = ParseTimestampString("00:00:0.031")
print(Result.hours)
print(Result.minutes)
print(Result.seconds)
print(Result.milliseconds)
This should returns:
> Result = ParseTimestampString("00:00:0.031")
>
> print(Result.hours)
0
> print(Result.minutes)
0
> print(Result.seconds)
0
> print(Result.milliseconds)
31
Here is a not bad way using string.gmatch which is splitting by regex in Lua. Here the value is being split by either ":" or ".". Then there is a counter in place to match the index for the resulting table.
local t = "00:00:0.031"
local ft = {
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0
}
local count = 1
for str in string.gmatch(t, "([^:|.]+)") do
ft[count] = tonumber(str)
count = count + 1
end
You can do a printing loop afterwards to check the results
for i = 1, 4 do
print(ft[i])
end
Output:
0
0
0
31
The main problem I have found with my solution is that it does not save the values under the keys listed but instead the numbers 1 2 3 4.
My Simplest Answer Will Be Just Split the given string by your regex, in This Case For HOUR:MIN:SEC.MS
first Split By (:) To Get HOUR MIN & SEC+MS, Then Split SEC+MS by (.) To separate Both seconds And milliseconds
Below is my answer in java
import java.util.*;
class timeX {
long hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 31;
//Convert Given Time String To Vars
timeX(String input) {
//Split Input By (:) For Hour, Minutes & Seconds+Miliseconds
String[] splitted=input.split(":");
this.hours=Long.parseLong(splitted[0]);
this.minutes=Long.parseLong(splitted[1]);
//Split Again For Seconds And Miliseconds By (.)
String[] splittedMandS=splitted[2].split("\\.");
this.seconds=Long.parseLong(splittedMandS[0]);
this.milliseconds=Long.parseLong(splittedMandS[1]);
}
}
public class Main
{
public static void main(String[] args)
{
timeX tmp = new timeX("30:20:2.031");
System.out.println("H: "+tmp.hours+" M: "+tmp.minutes+" S: "+tmp.seconds+" MS: "+tmp.milliseconds);
}
}
With Lua you can do...
The os.date() can be a format tool for seconds.
...but depends on Operating System.
This works on Linux but not (as i know so far) on MS-Windows.
print(os.date('%H:%M:%S',0-3600)) -- puts out: 00:00:00
print(os.date('%H:%M:%S',300-3600)) -- puts out: 00:05:00
Also it can output the date/time as a table.
> tshow=function(tab) for k,v in pairs(tab) do print(k,'=',v) end end
> tshow(os.date('*t'))
day = 4
year = 2021
month = 11
hour = 11
yday = 308
isdst = false
min = 23
wday = 5
sec = 51
...and unfortunally it has no milliseconds.
If the table output of os.date() is saved as a table...
> ttable=os.date('*t')
> os.time(ttable)
1636021672
> os.date(_,os.time(ttable))
Thu Nov 4 11:27:52 2021
> os.date('%H:%M:%S',os.time(ttable))
11:27:52
...then its key/value pairs can be used for: os.time()
Further code do nearly what you expect when in ttable key 1 is your time with milliseconds as a string...
local tshow=function(tab) for k,v in pairs(tab) do print(k,'=',v) end end
local ttable=os.date('*t') -- Create a time table
ttable[1]='0:0:0.31' -- Numbered keys in sequence are ignored by os.tim()
ttable[2]=ttable[1]:gsub('(%d+):(%d+):(%d+)[.](%d+)','return {year=ttable.year,month=ttable.month,day=ttable.day,hour=%1,min=%2,sec=%3,milliseconds=%4}')
-- That creates ttable[2] with the value:
--- return {year=ttable.year,month=ttable.month,day=ttable.day,hour=0,min=0,sec=0,milliseconds=31}
-- Lets convert it now to a table with...
ttable[2]=load(ttable[2])()
-- Using tshow() to look inside
tshow(ttable[2])
That will output...
milliseconds = 31
day = 4
year = 2021
hour = 0
month = 11
min = 0
sec = 0
And this will put it out formated with os.date()
print(os.date('%H:%M:%S.'..ttable[2].milliseconds,os.time(ttable[2])))
-- Output: 00:00:00.31
How can I reduce a specific duration from a date?
for example -
the base date and time to reduce from
15/05/2018 02:00:00
the duration to reduce -
03:00:00 hours
the expected output -
14/05/2018 23:00:00
=A1-3/24-5/(24*60)-55/(24*60*60)
where
A1 = 15/05/2018 02:00:00
3 = the number of hours to reduce
5 = minutes
55 = seconds
If you have time in format: 03:05:55, the formula is simple:
=A1 - A2
where
A1 = 15/05/2018 02:00:00
A2 = 03:05:55
I want to store duration of time in a Double and need to extract high and low values of Double (hour and minute) for accessing them. I also need to be able to set Double with two Ints (hour and minute).And I got something here now:
extension Double {
func hour() -> Int {
return NSNumber(double: floor(self)).integerValue
}
func minute() -> Int {
return NSNumber(float: Float(Double((self - floor(self)) * 100))).integerValue
}
init(hour: Int, minute: Int) {
self = Double(hour) + ( Double(minute) / 100 )
}
}
And then I've performed some testing with this in my appDelegate's didFinishLaunchingWithOptions:
var time: Double = 18.30
NSLog("Time is \"%f\" - so hours is \"%d\" and minutes is \"%d\".", time, time.hour(), time.minute())
time = Double(hour: 10, minute: 1)
NSLog("Time is \"%f\" - so hours is \"%d\" and minutes is \"%d\".", time, time.hour(), time.minute())
time = Double(hour: 15, minute: 45)
NSLog("Time is \"%f\" - so hours is \"%d\" and minutes is \"%d\".", time, time.hour(), time.minute())
Now, this code works. One might wonder why I convert Double to Float in the minute() function. This is because of an unknown issue that I faced when using Doubles without converting them to Floats before converting these Floats to Ints. If minutes didn't end with 0, one minute was subtracted for unknown reasons.For example, 10:42 returned 10 hours and 41 minutes. But 10:30 was still 10 hours and 30 minutes.Also 10:00 was 10 hours and 0 minutes.
This routine that I posted here seems to be working, but I was just wondering, if I am as efficient as possible... There's more conversion here than what would be needed.So, any improvements?
And does someone know the reason for unknown issue with decremented minute I mentioned?
A binary floating point number such as Double or Float cannot represent the number 10.42 exactly, therefore
multiplying the fractional part by 100 and truncating the result might give 41.
With the conversion to Float you are just "hiding" the problem.
Here is a version that rounds instead of truncating, and is overall a bit simpler. I have adopted the notation of "minute" from your code,
even if it represents 1/100 of an hour and not 1/60.
extension Double {
func hour() -> Int {
return Int(self)
}
func minute() -> Int {
return Int(round(self * 100.0)) % 100
}
init(hour: Int, minute: Int) {
self = Double(hour) + ( Double(minute) / 100 )
}
}
Other possible approaches to solve your problem:
Store the duration as an integer representing the total
number of minutes. E.g. "10:42" would be stored as 10*60 + 42.
Then you have no rounding problems at all.
Use the Foundation
type NSDecimalNumber instead of Double, which can represent
a decimal integer with up to 38 digits exactly.
I'm attempting to convert MPH into minute miles. I'm currently running code to do this by doing 60 / the miles per hour which gives me the result in minute miles.
For example 60/8mph = 7.5
However the answer I get I need to convert into minutes and seconds so that I would have 7 minutes 30 seconds. Is there a way I can get the numbers after the decimal point so I can multiply it by 60 to convert it to seconds, then add it back to the minutes.
You can use remainder,
double remainder = fmod(a_double, another_double);
should include <math.h>
Well, I don't know whether there is an existing class that handles this, but to answer your specific question, the fractional part of the decimal (mantissa?) would be:
((60 % 8) / 8.0f)
You can multiply that by 60.
Do it in seconds...
3600/8 = 450
450/60 = 7 remainder 30
= 7:30
It's pretty simple, you're on the right path actually.
What you need to do is:
Get Minutes
Get Seconds
Convert seconds from int to real time (0.5 to 30, etc..)
Add seconds to minutes
Get minutes by casting it to an Integer:
int minutes = 60/8;
Get seconds by using the remainder:
float seconds = 60%8;
Convert seconds to real time:
int realSeconds = seconds * 60;
Now get result back by adding both:
int totalSeconds = minuts + realSeconds;
Here's a little function that does it (typed directly to browser, probably won't compile)
#include <math.h>
int getMinuteMiles(float mph){
int minutes = 60/mph;
double seconds = fmod(60, mph);
int realSeconds = seconds * 60;
return minutes+realSeconds;
}
I need a custom function to calculate the times given from a certain point in the future X
It should countdown from 1 hour to zero
1 hour
59 min
59 min
..
10 min
9 min
..
1 min
59 sec
58 sec
57 sec
..
1 sec
Im currently using the
= clean_text distance_of_time_in_words(Time.now, real_time, true)
With the clean_text function:
def clean_text(string)
bad_words = ["less than", "about"]
change_words = ["hours", "minutes"]
bad_words.each do |bad|
string.gsub!(bad + " ", '')
end
string = string.gsub("hours", "hrs")
string = string.gsub("minutes", "min")
string = string.gsub("minute", "min")
string = string.gsub("half a min", "30 sec")
string = string.gsub("seconds", "sec")
return string
end
But this is insufficient since Im rewriting "minutes" to "min" etc. What would be a good start to write such a custom function for time? I guess it will be quite complex but wondered if there are any rails internal functions I could use?
I need
countdown like listed above
it has to be i18n compatible so I can do 1 hour / 1 houra, etc
Anyone an idea or will it be a custom function thats really neccesairly here?