Search code examples
javascriptdatedate-format

Convert a countdown like date format to milliseconds in JavaScript


I have to convert this countdown-like Date format 0d0h0m0s to milliseconds. The format can optionally have 0d, 0h, 0m heading values, hence admitted values are

1d23h10m
0d12h0m
12h0m
0m0s
0m10s
10s

while at least one trailing 0s format value is required, the 0 value is optional for each of the dhm formats, so 0m5s and 5s are both admitted values.

Since this function will be applied N times per sec. (N between 10 and 100), there is a performances constraint for each function execution time.

NOTE. It's possible to use a simple Regex pattern to split the string like /[dhms]/gi into date components for day, hour, minutes and seconds, but I was looking to a date formatting safe approach.


Solution

  • One option would be to extract all matches with a regular expression, and then multiply and sum as needed:

    const re = /(?:(\d+)y)?(?:(\d+)m)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/;
    const toSeconds = input => {
      const [, years, months, days, hours, minutes, seconds] = input.match(re);
      // console.log({years, months, days, hours, minutes, seconds})
      const totalDays = ((years || 0) * 365)
        + ((months || 0) * 30)
        + (days || 0);
      const totalSeconds = totalDays * 24 * 3600
        + ((hours || 0)*3600)
        + ((minutes || 0) * 60)
        + (seconds || 0)
      return totalSeconds * 1000;
    };
    `1d23h10m
    0d12h0m
    12h0m
    0m0s
    0m10s
    10s`.split('\n').forEach(str => console.log(toSeconds(str)));

    Of course, if you want a different calculation (such as 365.25 days per year, or something like that), such a tweak would be quite easy to implement.