Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #368 Parse a millisecond value

Parse the millisecond value a, to a collection of duration values, m.

For example, `1,000,000 ms` is `{min=16, sec=40}`.

https://en.wikipedia.org/wiki/Gregorian_calendar
https://en.wikipedia.org/wiki/Time

u = [('ms', 1)]
def units(x, y):
    u.append((x, y * u[-1][1]))
units('s', 1_000)
units('m', 60)
units('h', 60)
units('d', 24)
units('y', 365.2425)
m, x = dict(), a
for u in reversed(u):
    if x >= (y := u[1]):
        m[u], x = divmod(x, y)
class Units:
    def __init__(self, x, y):
        self.a = [(x, y)]
    def set(self, x, y):
        a = self.a
        a.append((x, y * a[-1][1]))
    def get(self, x):
        m = dict()
        for y, z in reversed(self.a):
            if x >= z:
                m[y], x = divmod(x, z)
        return m
u = Units('ms', 1)
u.set('s', 1_000)
u.set('m', 60)
u.set('h', 60)
u.set('d', 24)
u.set('y', 365.2425)
m = u.get(a)
import static java.util.List.of;
import java.util.LinkedHashMap;
import java.util.Map;
enum Unit {
    ms(1), s(1_000 * ms.x), m(60 * s.x),
    h(60 * m.x), d(24 * h.x),
    y(365.2425 * d.x);
    double x;
    Unit(double x) { this.x = x; }
    static Map<Unit, Integer> parse(long ms) {
        Map m = new LinkedHashMap<>();
        double x = ms, y;
        for (Unit u : of(values()).reversed())
            if (x >= (y = u.x)) {
                m.put(u, (int) (x / y));
                x = x % y;
            }
        return m;
    }
}
Map<Unit, Integer> m = Unit.parse(a);
math
Type
   TT = record H, M, S, Ms: Integer; end;
   TTList = array of TT;
var
  t: TT;
  m: TTList;
  a: Integer;
begin
...
  divmod(a, MSecsPerSec*SecsPerHour, t.H, a);
  divmod(a, MSecsPerSec*SecsPerMin, t.M, a);
  divmod(a, MSecsPerSec, t.S, t.Ms);
  SetLength(m, Length(m)+1);
  m[High(m)] := t;
...
DURATIONS = {years: 525_949_200, days: 1_440_000, hrs: 60_000, sec: 1000, ms: 1}

m = DURATIONS.each_with_object({}) {|(k, v), h|  h[k], mod = mod.divmod(v) }

New implementation...
< >
reilas