Programming Search⌘K

Taskintro

Format a duration

Also called format seconds as hours minutes and seconds, seconds to HH:MM:SS, format elapsed time, duration to string, format a time span, ISO 8601 duration, human-readable duration, Intl.DurationFormat, TimeSpan format, timedelta to string.

Show a number of seconds as hours, minutes and seconds, such as 25:01:01. The hours do not wrap at 24, and a negative duration gets a minus sign. Also the ISO 8601 and human-readable forms.

Task

Show a duration, given as a whole number of seconds, as hours, minutes and seconds. For example, 3723 seconds is 01:02:03, and 90061 seconds is 25:01:01.

The contract format_duration(seconds) takes an integer from -10^15 to 10^15 and returns text in the form HH:MM:SS:

  • MM and SS have two digits each, from 00 to 59.
  • HH is the whole number of hours, with at least two digits. The hours do not wrap at 24, and there is no field for days. So one day is 24:00:00 and one week is 168:00:00.
  • A negative duration starts with a minus sign, and the fields are those of the magnitude. So -61 seconds is -00:01:01.

A duration is an amount of time, such as the time that a job took. It is not a time of day, so a time-of-day formatter is the wrong tool. See the pitfalls.

The arithmetic is short. Take the magnitude a of the number. The hours are a / 3600, the minutes are a % 3600 / 60, and the seconds are a % 60, with integer division. Then put the sign in front.

There are two other common forms of a duration:

  • ISO 8601. Durations "are represented by the format P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W". 90061 seconds is PT25H1M1S, or P1DT1H1M1S with a day field. A day in a calendar is not always 24 hours long, so the two forms are not always the same amount of time.
  • Human-readable text, such as 25 hours, 1 minute, 1 second or 25h1m1s. The words and their order depend on the language.

Solutions

  • Python. divmod(abs(seconds), 60) and divmod(minutes, 60) give the fields, and the f-string format 02d pads them. The test compares the result with str(timedelta(seconds=n)) for durations that are shorter than a day.
  • JavaScript. Math.floor divides, and padStart(2, "0") pads. A number holds every integer up to 2^53 exactly, so 10^15 is safe.
  • TypeScript. The same code as JavaScript, with types.
  • Java. Duration.ofSeconds(seconds).abs() gives the fields with toHours(), toMinutesPart() and toSecondsPart(). toHours() does not wrap at 24. String.format pads with %02d.
  • C#. The function divides a long and pads with the format 00 and CultureInfo.InvariantCulture. The test shows that TimeSpan.FromSeconds(1e15) throws an OverflowException, so a TimeSpan cannot hold all of the range.
  • Go. The function divides an int64 and formats with fmt.Sprintf("%s%02d:%02d:%02d", ...). It does not use time.Duration, which holds nanoseconds and overflows for large values. See the pitfalls.
  • Rust. i64::unsigned_abs gives the magnitude as a u64, so the function is also correct for i64::MIN. The format {:02} of format! pads. std::time::Duration has no sign: checked_sub returns None "if the result would be negative".
  • C. The caller gives a buffer of FORMAT_DURATION_SIZE bytes, and snprintf writes %s%02llu:%02llu:%02llu. The magnitude is an unsigned long long, so LLONG_MIN does not overflow.
  • C++. std::format("{:%T}", std::chrono::seconds{seconds}). cppreference says that %T is "Equivalent to "%H:%M:%S"", and it describes %H as "the hour (24-hour clock)". For a duration, libstdc++ of GCC 15 does not wrap the hours, and it writes a minus sign for a negative duration. The tests check 24:00:00, 25:01:01 and the negative cases, so they find a library that wraps.
  • Bash. Shell arithmetic with / and %, and printf '%s%02d:%02d:%02d\n'. The tests include 10^15 and -10^15.

The standard libraries also have other forms. A Go time.Duration writes itself "in the form "72h3m0.5s". Leading zero units are omitted.":

package main

import (
	"fmt"
	"time"
)

func main() {
	for _, s := range []int64{0, 60, 3723, 90061, -61} {
		fmt.Println(time.Duration(s) * time.Second)
	}
}
Output
0s
1m0s
1h2m3s
25h1m1s
-1m1s

Java Duration.toString() writes ISO 8601: "The format of the returned string will be PTnHnMnS, where n is the relevant hours, minutes or seconds part of the duration". For a negative duration, each part has a minus sign:

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        for (long s : new long[] {3723, 90061, -61}) {
            Duration d = Duration.ofSeconds(s);
            Duration a = d.abs();
            String hms = String.format("%s%02d:%02d:%02d",
                    d.isNegative() ? "-" : "", a.toHours(), a.toMinutesPart(), a.toSecondsPart());
            System.out.println(d + " " + hms);
        }
    }
}
Output
PT1H2M3S 01:02:03
PT25H1M1S 25:01:01
PT-1M-1S -00:01:01

In JavaScript, "The Intl.DurationFormat object enables language-sensitive duration formatting". It takes the fields, not a number of seconds, and it does not move seconds into minutes and hours. The style digital writes one digit for an hour less than 10:

const d = { hours: 25, minutes: 1, seconds: 1 };
for (const style of ["long", "short", "narrow", "digital"]) {
  console.log(new Intl.DurationFormat("en", { style }).format(d));
}
console.log(new Intl.DurationFormat("en", { style: "long" }).format({ seconds: 90061 }));
console.log(new Intl.DurationFormat("en", { style: "digital" }).format({ hours: 1, minutes: 1, seconds: 1 }));
Output
25 hours, 1 minute, 1 second
25 hr, 1 min, 1 sec
25h 1m 1s
25:01:01
90,061 seconds
1:01:01

In C++, a duration with no format writes its count and its unit. hh_mm_ss "splits a std::chrono::duration into a "broken down" time such as hours : minutes : seconds", and %T uses the same fields:

#include <chrono>
#include <format>
#include <iostream>

int main() {
    using namespace std::chrono;
    for (const seconds s : {3723s, 90061s, -61s}) {
        std::cout << std::format("{} {:%T}", s, s) << "\n";
    }
    const hh_mm_ss<seconds> parts{90061s};
    std::cout << parts.hours().count() << " " << parts.minutes().count() << " " << parts.seconds().count() << "\n";
}
Output
3723s 01:02:03
90061s 25:01:01
-61s -00:01:01
25 1 1

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • just-under-an-hour and just-under-a-day: 3599 and 86399 seconds give 00:59:59 and 23:59:59. One more second carries into the next field.
  • one-day, more-than-a-day, hundred-hours, one-week and one-year: the hours do not wrap at 24, and they can have more than two digits, such as 100:00:00 and 8760:00:00.
  • minus-one-second, negative-minute, negative-hours and negative-day: the sign comes first, and the fields are those of the magnitude, such as -00:00:01.
  • beyond-go-duration: 10^10 seconds is about 317 years. A Go time.Duration cannot hold it, and the result is 2777777:46:40.
  • largest and most-negative: 10^15 and -10^15 seconds. A C# TimeSpan cannot hold them, and a JavaScript number holds them exactly.

Pitfalls

  • Python str(timedelta). The form is "[D day[s], ][H]H:MM:SS[.UUUUUU] , where D is negative for negative t". So a day is a separate field, the hours have one digit, and a negative duration has a negative number of days and positive hours. The documentation says: "Note that normalization of negative values may be surprising at first."

This code runs but gives a wrong answer on purpose.

from datetime import timedelta

for s in (3723, 90061, -61):
    print(str(timedelta(seconds=s)))
Output
1:02:03
1 day, 1:01:01
-1 day, 23:58:59
  • Division of a negative number. In Python, //, % and divmod round down, so the remainder of a negative number is positive. In C, C++, Java, C#, Go, Rust and JavaScript, the remainder has the sign of the dividend. Both give wrong fields for a negative duration. Divide the magnitude and put the sign in front:

This code runs but gives a wrong answer on purpose.

seconds = -61
print(divmod(seconds, 60))
minutes, s = divmod(seconds, 60)
hours, m = divmod(minutes, 60)
print(f"{hours:02d}:{m:02d}:{s:02d}")
Output
(-2, 59)
-1:58:59
  • A time-of-day formatter. A Date is an instant, and toISOString writes its time of day. "The timezone is always UTC". Seconds from the epoch as a time of day wrap at 24 hours, and a negative duration gives a time on the day before:

This code runs but gives a wrong answer on purpose.

for (const s of [3723, 90061, -61]) {
  console.log(new Date(s * 1000).toISOString().slice(11, 19));
}
Output
01:02:03
01:01:01
23:58:59

GNU date does the same with the format sequence %T, which is "time; same as %H:%M:%S":

This code runs but gives a wrong answer on purpose.

date -u -d @3723 +%T
date -u -d @90061 +%T
date -u -d @-61 +%T
Output
01:02:03
01:01:01
23:58:59
  • C# custom TimeSpan formats. The format hh is "The number of whole hours in the time interval that aren't counted as part of days", so hh\:mm\:ss drops the days. The documentation says: "Custom TimeSpan format specifiers also don't include a sign symbol that enables you to differentiate between negative and positive time intervals." The standard format c keeps the sign, but it writes the days as a separate field:

This code runs but gives a wrong answer on purpose.

foreach (int s in new[] { 3723, 90061, -61 })
{
    TimeSpan t = TimeSpan.FromSeconds(s);
    Console.WriteLine(t.ToString(@"hh\:mm\:ss") + " " + t.ToString("c"));
}
Output
01:02:03 01:02:03
01:01:01 1.01:01:01
00:01:01 -00:01:01
  • Go time.Duration overflows. "A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years." A multiplication with time.Second that overflows does not give an error. It gives a wrong duration:

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"time"
)

func main() {
	var seconds int64 = 10_000_000_000
	fmt.Println(time.Duration(seconds) * time.Second)
	fmt.Println(seconds/3600, seconds%3600/60, seconds%60)
}
Output
-2346317h47m53.709551616s
2777777 46 40

With a constant in place of the variable, the Go compiler finds the overflow and stops.

See ISO 8601 for the duration form PnYnMnDTnHnMnS.

Code

The build runs the native tests of each language in a pinned toolchain.

duration.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-duration/.


def format_duration(seconds: int) -> str:
    """Return the duration as HH:MM:SS. The hours do not wrap at 24."""
    sign = "-" if seconds < 0 else ""
    minutes, s = divmod(abs(seconds), 60)
    hours, m = divmod(minutes, 60)
    return f"{sign}{hours:02d}:{m:02d}:{s:02d}"
test_duration.py 40 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-duration/.

from datetime import timedelta

import pytest

from duration import format_duration

CASES = [
    ("zero", 0, "00:00:00"),
    ("seconds-only", 59, "00:00:59"),
    ("one-minute", 60, "00:01:00"),
    ("one-hour", 3600, "01:00:00"),
    ("hours-minutes-seconds", 3723, "01:02:03"),
    ("just-under-an-hour", 3599, "00:59:59"),
    ("just-under-a-day", 86399, "23:59:59"),
    ("one-day", 86400, "24:00:00"),
    ("more-than-a-day", 90061, "25:01:01"),
    ("hundred-hours", 360000, "100:00:00"),
    ("one-week", 604800, "168:00:00"),
    ("one-year", 31536000, "8760:00:00"),
    ("minus-one-second", -1, "-00:00:01"),
    ("negative-minute", -61, "-00:01:01"),
    ("negative-hours", -3723, "-01:02:03"),
    ("negative-day", -90061, "-25:01:01"),
    ("beyond-go-duration", 10000000000, "2777777:46:40"),
    ("largest", 1000000000000000, "277777777777:46:40"),
    ("most-negative", -1000000000000000, "-277777777777:46:40"),
]


@pytest.mark.parametrize("name,seconds,want", CASES, ids=[c[0] for c in CASES])
def test_cases(name, seconds, want):
    assert format_duration(seconds) == want


def test_same_as_timedelta_under_a_day():
    for seconds in range(0, 86400, 997):
        assert format_duration(seconds) == str(timedelta(seconds=seconds)).zfill(8)
duration.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

#ifndef FORMAT_DURATION_HPP
#define FORMAT_DURATION_HPP

#include <chrono>
#include <format>
#include <string>

// Returns the duration as HH:MM:SS. For a duration, %T does not wrap the
// hours at 24, and it writes a minus sign for a negative duration.
inline std::string format_duration(long long seconds) {
    return std::format("{:%T}", std::chrono::seconds{seconds});
}

#endif
test_duration.cpp 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

#include <chrono>
#include <cstdio>
#include <string>

#include "duration.hpp"

namespace {

struct test_case {
    const char* name;
    long long seconds;
    const char* want;
};

const test_case cases[] = {
    {"zero", 0LL, "00:00:00"},
    {"seconds-only", 59LL, "00:00:59"},
    {"one-minute", 60LL, "00:01:00"},
    {"one-hour", 3600LL, "01:00:00"},
    {"hours-minutes-seconds", 3723LL, "01:02:03"},
    {"just-under-an-hour", 3599LL, "00:59:59"},
    {"just-under-a-day", 86399LL, "23:59:59"},
    {"one-day", 86400LL, "24:00:00"},
    {"more-than-a-day", 90061LL, "25:01:01"},
    {"hundred-hours", 360000LL, "100:00:00"},
    {"one-week", 604800LL, "168:00:00"},
    {"one-year", 31536000LL, "8760:00:00"},
    {"minus-one-second", -1LL, "-00:00:01"},
    {"negative-minute", -61LL, "-00:01:01"},
    {"negative-hours", -3723LL, "-01:02:03"},
    {"negative-day", -90061LL, "-25:01:01"},
    {"beyond-go-duration", 10000000000LL, "2777777:46:40"},
    {"largest", 1000000000000000LL, "277777777777:46:40"},
    {"most-negative", -1000000000000000LL, "-277777777777:46:40"},
};

}  // namespace

int main() {
    int failures = 0;
    for (const test_case& c : cases) {
        const std::string got = format_duration(c.seconds);
        if (got != c.want) {
            std::printf("FAIL %s: %s\n", c.name, got.c_str());
            ++failures;
        }
    }
    // hh_mm_ss gives the same fields.
    const std::chrono::hh_mm_ss<std::chrono::seconds> h{std::chrono::seconds{-90061}};
    if (!h.is_negative() || h.hours().count() != 25 || h.minutes().count() != 1 || h.seconds().count() != 1) {
        std::printf("FAIL hh_mm_ss\n");
        ++failures;
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
DurationFormat.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

import java.time.Duration;

/** Formats a duration in seconds as HH:MM:SS. */
public final class DurationFormat {
    private DurationFormat() {}

    /** Returns the duration as HH:MM:SS. The hours do not wrap at 24. */
    public static String formatDuration(long seconds) {
        Duration d = Duration.ofSeconds(seconds).abs();
        String sign = seconds < 0 ? "-" : "";
        return String.format("%s%02d:%02d:%02d", sign, d.toHours(), d.toMinutesPart(), d.toSecondsPart());
    }
}
DurationFormatTest.java 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.time.Duration;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class DurationFormatTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("zero", 0L, "00:00:00"),
                Arguments.of("seconds-only", 59L, "00:00:59"),
                Arguments.of("one-minute", 60L, "00:01:00"),
                Arguments.of("one-hour", 3600L, "01:00:00"),
                Arguments.of("hours-minutes-seconds", 3723L, "01:02:03"),
                Arguments.of("just-under-an-hour", 3599L, "00:59:59"),
                Arguments.of("just-under-a-day", 86399L, "23:59:59"),
                Arguments.of("one-day", 86400L, "24:00:00"),
                Arguments.of("more-than-a-day", 90061L, "25:01:01"),
                Arguments.of("hundred-hours", 360000L, "100:00:00"),
                Arguments.of("one-week", 604800L, "168:00:00"),
                Arguments.of("one-year", 31536000L, "8760:00:00"),
                Arguments.of("minus-one-second", -1L, "-00:00:01"),
                Arguments.of("negative-minute", -61L, "-00:01:01"),
                Arguments.of("negative-hours", -3723L, "-01:02:03"),
                Arguments.of("negative-day", -90061L, "-25:01:01"),
                Arguments.of("beyond-go-duration", 10000000000L, "2777777:46:40"),
                Arguments.of("largest", 1000000000000000L, "277777777777:46:40"),
                Arguments.of("most-negative", -1000000000000000L, "-277777777777:46:40"));
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void format(String name, long seconds, String want) {
        assertEquals(want, DurationFormat.formatDuration(seconds));
    }

    @Test
    void isoForm() {
        assertEquals("PT25H1M1S", Duration.ofSeconds(90061).toString());
        assertEquals("PT-1M-1S", Duration.ofSeconds(-61).toString());
    }
}
duration.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

#include "duration.h"

#include <stdio.h>

void format_duration(long long seconds, char out[FORMAT_DURATION_SIZE]) {
    // The magnitude is unsigned, so -LLONG_MIN does not overflow.
    const unsigned long long a =
        seconds < 0 ? 0ULL - (unsigned long long)seconds : (unsigned long long)seconds;
    snprintf(out, FORMAT_DURATION_SIZE, "%s%02llu:%02llu:%02llu", seconds < 0 ? "-" : "",
             a / 3600, a % 3600 / 60, a % 60);
}
duration.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

#ifndef FORMAT_DURATION_H
#define FORMAT_DURATION_H

// Room for a sign, the hours of any long long and ":MM:SS".
#define FORMAT_DURATION_SIZE 32

// Writes the duration as HH:MM:SS to out. The hours do not wrap at 24.
void format_duration(long long seconds, char out[FORMAT_DURATION_SIZE]);

#endif
test_duration.c 60 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

#include "duration.h"

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name;
    long long seconds;
    const char *want;
};

static const struct test_case cases[] = {
    {"zero", 0LL, "00:00:00"},
    {"seconds-only", 59LL, "00:00:59"},
    {"one-minute", 60LL, "00:01:00"},
    {"one-hour", 3600LL, "01:00:00"},
    {"hours-minutes-seconds", 3723LL, "01:02:03"},
    {"just-under-an-hour", 3599LL, "00:59:59"},
    {"just-under-a-day", 86399LL, "23:59:59"},
    {"one-day", 86400LL, "24:00:00"},
    {"more-than-a-day", 90061LL, "25:01:01"},
    {"hundred-hours", 360000LL, "100:00:00"},
    {"one-week", 604800LL, "168:00:00"},
    {"one-year", 31536000LL, "8760:00:00"},
    {"minus-one-second", -1LL, "-00:00:01"},
    {"negative-minute", -61LL, "-00:01:01"},
    {"negative-hours", -3723LL, "-01:02:03"},
    {"negative-day", -90061LL, "-25:01:01"},
    {"beyond-go-duration", 10000000000LL, "2777777:46:40"},
    {"largest", 1000000000000000LL, "277777777777:46:40"},
    {"most-negative", -1000000000000000LL, "-277777777777:46:40"},
};

int main(void) {
    int failures = 0;
    char out[FORMAT_DURATION_SIZE];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        format_duration(c->seconds, out);
        if (strcmp(out, c->want) != 0) {
            printf("FAIL %s: %s\n", c->name, out);
            failures++;
        }
    }
    format_duration(LLONG_MIN, out);
    if (strcmp(out, "-2562047788015215:30:08") != 0) {
        printf("FAIL LLONG_MIN: %s\n", out);
        failures++;
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
DurationFormat.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

using System;
using System.Globalization;

/// <summary>Formats a duration in seconds as HH:MM:SS.</summary>
public static class DurationFormat
{
    /// <summary>
    /// Returns the duration as HH:MM:SS. The hours do not wrap at 24. The method divides a long, so
    /// it has no TimeSpan and no TimeSpan limit.
    /// </summary>
    public static string FormatDuration(long seconds)
    {
        string sign = seconds < 0 ? "-" : "";
        long a = Math.Abs(seconds);
        return string.Format(
            CultureInfo.InvariantCulture, "{0}{1:00}:{2:00}:{3:00}", sign, a / 3600, a % 3600 / 60, a % 60);
    }
}
DurationFormatTests.cs 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

using System;
using Xunit;

public sealed class DurationFormatTests
{
    public static TheoryData<string, long, string> Cases => new()
    {
        { "zero", 0L, "00:00:00" },
        { "seconds-only", 59L, "00:00:59" },
        { "one-minute", 60L, "00:01:00" },
        { "one-hour", 3600L, "01:00:00" },
        { "hours-minutes-seconds", 3723L, "01:02:03" },
        { "just-under-an-hour", 3599L, "00:59:59" },
        { "just-under-a-day", 86399L, "23:59:59" },
        { "one-day", 86400L, "24:00:00" },
        { "more-than-a-day", 90061L, "25:01:01" },
        { "hundred-hours", 360000L, "100:00:00" },
        { "one-week", 604800L, "168:00:00" },
        { "one-year", 31536000L, "8760:00:00" },
        { "minus-one-second", -1L, "-00:00:01" },
        { "negative-minute", -61L, "-00:01:01" },
        { "negative-hours", -3723L, "-01:02:03" },
        { "negative-day", -90061L, "-25:01:01" },
        { "beyond-go-duration", 10000000000L, "2777777:46:40" },
        { "largest", 1000000000000000L, "277777777777:46:40" },
        { "most-negative", -1000000000000000L, "-277777777777:46:40" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Format(string name, long seconds, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, DurationFormat.FormatDuration(seconds));
    }

    [Fact]
    public void TimeSpanRange()
    {
        Assert.Equal("1.01:01:01", TimeSpan.FromSeconds(90061).ToString());
        Assert.Throws<OverflowException>(() => TimeSpan.FromSeconds(1e15));
    }
}
duration.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

const pad = (n) => String(n).padStart(2, "0");

// Returns the duration as HH:MM:SS. The hours do not wrap at 24. The seconds
// must be a safe integer, so the arithmetic on numbers is exact.
export function formatDuration(seconds) {
  const sign = seconds < 0 ? "-" : "";
  const a = Math.abs(seconds);
  const hours = Math.floor(a / 3600);
  const minutes = Math.floor((a % 3600) / 60);
  return `${sign}${pad(hours)}:${pad(minutes)}:${pad(a % 60)}`;
}
duration.test.js 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { formatDuration } from "./duration.js";

const cases = [
  ["zero", 0, "00:00:00"],
  ["seconds-only", 59, "00:00:59"],
  ["one-minute", 60, "00:01:00"],
  ["one-hour", 3600, "01:00:00"],
  ["hours-minutes-seconds", 3723, "01:02:03"],
  ["just-under-an-hour", 3599, "00:59:59"],
  ["just-under-a-day", 86399, "23:59:59"],
  ["one-day", 86400, "24:00:00"],
  ["more-than-a-day", 90061, "25:01:01"],
  ["hundred-hours", 360000, "100:00:00"],
  ["one-week", 604800, "168:00:00"],
  ["one-year", 31536000, "8760:00:00"],
  ["minus-one-second", -1, "-00:00:01"],
  ["negative-minute", -61, "-00:01:01"],
  ["negative-hours", -3723, "-01:02:03"],
  ["negative-day", -90061, "-25:01:01"],
  ["beyond-go-duration", 10000000000, "2777777:46:40"],
  ["largest", 1000000000000000, "277777777777:46:40"],
  ["most-negative", -1000000000000000, "-277777777777:46:40"],
];

for (const [name, seconds, want] of cases) {
  test(name, () => {
    assert.equal(formatDuration(seconds), want);
  });
}
duration.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

const pad = (n: number): string => String(n).padStart(2, "0");

// Returns the duration as HH:MM:SS. The hours do not wrap at 24. The seconds
// must be a safe integer, so the arithmetic on numbers is exact.
export function formatDuration(seconds: number): string {
  const sign = seconds < 0 ? "-" : "";
  const a = Math.abs(seconds);
  const hours = Math.floor(a / 3600);
  const minutes = Math.floor((a % 3600) / 60);
  return `${sign}${pad(hours)}:${pad(minutes)}:${pad(a % 60)}`;
}
duration.test.ts 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { formatDuration } from "./duration.ts";

const cases: [string, number, string][] = [
  ["zero", 0, "00:00:00"],
  ["seconds-only", 59, "00:00:59"],
  ["one-minute", 60, "00:01:00"],
  ["one-hour", 3600, "01:00:00"],
  ["hours-minutes-seconds", 3723, "01:02:03"],
  ["just-under-an-hour", 3599, "00:59:59"],
  ["just-under-a-day", 86399, "23:59:59"],
  ["one-day", 86400, "24:00:00"],
  ["more-than-a-day", 90061, "25:01:01"],
  ["hundred-hours", 360000, "100:00:00"],
  ["one-week", 604800, "168:00:00"],
  ["one-year", 31536000, "8760:00:00"],
  ["minus-one-second", -1, "-00:00:01"],
  ["negative-minute", -61, "-00:01:01"],
  ["negative-hours", -3723, "-01:02:03"],
  ["negative-day", -90061, "-25:01:01"],
  ["beyond-go-duration", 10000000000, "2777777:46:40"],
  ["largest", 1000000000000000, "277777777777:46:40"],
  ["most-negative", -1000000000000000, "-277777777777:46:40"],
];

for (const [name, seconds, want] of cases) {
  test(name, () => {
    assert.equal(formatDuration(seconds), want);
  });
}
duration.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

// Package duration formats a duration in seconds as HH:MM:SS.
package duration

import "fmt"

// FormatDuration returns the duration as HH:MM:SS. The hours do not wrap at
// 24. A time.Duration holds only about 290 years, so the function takes the
// seconds as an int64.
func FormatDuration(seconds int64) string {
	sign := ""
	a := seconds
	if seconds < 0 {
		sign, a = "-", -seconds
	}
	return fmt.Sprintf("%s%02d:%02d:%02d", sign, a/3600, a%3600/60, a%60)
}
duration_test.go 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

package duration

import (
	"testing"
	"time"
)

var cases = []struct {
	name    string
	seconds int64
	want    string
}{
	{"zero", 0, "00:00:00"},
	{"seconds-only", 59, "00:00:59"},
	{"one-minute", 60, "00:01:00"},
	{"one-hour", 3600, "01:00:00"},
	{"hours-minutes-seconds", 3723, "01:02:03"},
	{"just-under-an-hour", 3599, "00:59:59"},
	{"just-under-a-day", 86399, "23:59:59"},
	{"one-day", 86400, "24:00:00"},
	{"more-than-a-day", 90061, "25:01:01"},
	{"hundred-hours", 360000, "100:00:00"},
	{"one-week", 604800, "168:00:00"},
	{"one-year", 31536000, "8760:00:00"},
	{"minus-one-second", -1, "-00:00:01"},
	{"negative-minute", -61, "-00:01:01"},
	{"negative-hours", -3723, "-01:02:03"},
	{"negative-day", -90061, "-25:01:01"},
	{"beyond-go-duration", 10000000000, "2777777:46:40"},
	{"largest", 1000000000000000, "277777777777:46:40"},
	{"most-negative", -1000000000000000, "-277777777777:46:40"},
}

func TestFormatDuration(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := FormatDuration(c.seconds); got != c.want {
				t.Errorf("got %s, want %s", got, c.want)
			}
		})
	}
}

func TestDurationString(t *testing.T) {
	if got := (90061 * time.Second).String(); got != "25h1m1s" {
		t.Errorf("got %s", got)
	}
}
duration.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

/// Returns the duration as HH:MM:SS. The hours do not wrap at 24.
/// std::time::Duration has no sign and no format of this kind, so the
/// function takes the seconds as an i64.
pub fn format_duration(seconds: i64) -> String {
    let sign = if seconds < 0 { "-" } else { "" };
    let a = seconds.unsigned_abs();
    format!("{sign}{:02}:{:02}:{:02}", a / 3600, a % 3600 / 60, a % 60)
}
tests/duration_test.rs 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/format-a-duration/.

use algo_format_a_duration::format_duration;

const CASES: &[(&str, i64, &str)] = &[
    ("zero", 0, "00:00:00"),
    ("seconds-only", 59, "00:00:59"),
    ("one-minute", 60, "00:01:00"),
    ("one-hour", 3600, "01:00:00"),
    ("hours-minutes-seconds", 3723, "01:02:03"),
    ("just-under-an-hour", 3599, "00:59:59"),
    ("just-under-a-day", 86399, "23:59:59"),
    ("one-day", 86400, "24:00:00"),
    ("more-than-a-day", 90061, "25:01:01"),
    ("hundred-hours", 360000, "100:00:00"),
    ("one-week", 604800, "168:00:00"),
    ("one-year", 31536000, "8760:00:00"),
    ("minus-one-second", -1, "-00:00:01"),
    ("negative-minute", -61, "-00:01:01"),
    ("negative-hours", -3723, "-01:02:03"),
    ("negative-day", -90061, "-25:01:01"),
    ("beyond-go-duration", 10000000000, "2777777:46:40"),
    ("largest", 1000000000000000, "277777777777:46:40"),
    ("most-negative", -1000000000000000, "-277777777777:46:40"),
];

#[test]
fn cases() {
    for &(name, seconds, want) in CASES {
        assert_eq!(format_duration(seconds), want, "{name}");
    }
}

#[test]
fn most_negative_i64() {
    assert_eq!(format_duration(i64::MIN), "-2562047788015215:30:08");
}
duration.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-duration/.

# format_duration SECONDS
# Prints the duration as HH:MM:SS. The hours do not wrap at 24. Bash
# arithmetic uses 64-bit integers.
format_duration() {
  local s=$1 sign=
  if ((s < 0)); then
    sign=-
    s=$((-s))
  fi
  printf '%s%02d:%02d:%02d\n' "$sign" "$((s / 3600))" "$((s % 3600 / 60))" "$((s % 60))"
}
test_duration.bats 27 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/format-a-duration/.

setup() {
  source "$BATS_TEST_DIRNAME/duration.sh"
}

@test "zero" { run format_duration 0; [ "$status" -eq 0 ]; [ "$output" = "00:00:00" ]; }
@test "seconds-only" { run format_duration 59; [ "$status" -eq 0 ]; [ "$output" = "00:00:59" ]; }
@test "one-minute" { run format_duration 60; [ "$status" -eq 0 ]; [ "$output" = "00:01:00" ]; }
@test "one-hour" { run format_duration 3600; [ "$status" -eq 0 ]; [ "$output" = "01:00:00" ]; }
@test "hours-minutes-seconds" { run format_duration 3723; [ "$status" -eq 0 ]; [ "$output" = "01:02:03" ]; }
@test "just-under-an-hour" { run format_duration 3599; [ "$status" -eq 0 ]; [ "$output" = "00:59:59" ]; }
@test "just-under-a-day" { run format_duration 86399; [ "$status" -eq 0 ]; [ "$output" = "23:59:59" ]; }
@test "one-day" { run format_duration 86400; [ "$status" -eq 0 ]; [ "$output" = "24:00:00" ]; }
@test "more-than-a-day" { run format_duration 90061; [ "$status" -eq 0 ]; [ "$output" = "25:01:01" ]; }
@test "hundred-hours" { run format_duration 360000; [ "$status" -eq 0 ]; [ "$output" = "100:00:00" ]; }
@test "one-week" { run format_duration 604800; [ "$status" -eq 0 ]; [ "$output" = "168:00:00" ]; }
@test "one-year" { run format_duration 31536000; [ "$status" -eq 0 ]; [ "$output" = "8760:00:00" ]; }
@test "minus-one-second" { run format_duration -1; [ "$status" -eq 0 ]; [ "$output" = "-00:00:01" ]; }
@test "negative-minute" { run format_duration -61; [ "$status" -eq 0 ]; [ "$output" = "-00:01:01" ]; }
@test "negative-hours" { run format_duration -3723; [ "$status" -eq 0 ]; [ "$output" = "-01:02:03" ]; }
@test "negative-day" { run format_duration -90061; [ "$status" -eq 0 ]; [ "$output" = "-25:01:01" ]; }
@test "beyond-go-duration" { run format_duration 10000000000; [ "$status" -eq 0 ]; [ "$output" = "2777777:46:40" ]; }
@test "largest" { run format_duration 1000000000000000; [ "$status" -eq 0 ]; [ "$output" = "277777777777:46:40" ]; }
@test "most-negative" { run format_duration -1000000000000000; [ "$status" -eq 0 ]; [ "$output" = "-277777777777:46:40" ]; }

References

  1. The Python Standard Library, datetime, timedelta objects, Supported operations, str(t)
  2. Java SE 21 API, java.time.Duration, toString()
  3. .NET documentation, Custom TimeSpan format strings, the introduction, before the table of format specifiers
  4. .NET documentation, Standard TimeSpan format strings, The constant ("c") format specifier
  5. Go standard library, time, type Duration; func (Duration) String
  6. cppreference.com, std::formatter<std::chrono::duration>, Format specification, %H and %T
  7. cppreference.com, std::chrono::hh_mm_ss, the description of the class
  8. MDN, Intl.DurationFormat, the description of the object
  9. MDN, Date.prototype.toISOString(), Description
  10. The Rust Standard Library, std::time::Duration, checked_sub
  11. Wikipedia, ISO 8601, Durations
  12. Linux manual page, date(1), the format sequence %T

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source