0 votes

I want to display elapsed playtime on screen. I currently have this time in seconds and want to convert it to HH:MM:SS format.

Is there a simple way to do this in Godot? For example, an in-built function?

asked Sep 7, 2018 in Engine by Diet Estus (1,453 points)
edited Sep 7, 2018 by Diet Estus

1 Answer

+1 vote
Best answer

No, I haven't stumbled upon built-in function for converting seconds into arbitrary time format. Nevertheless, based on a similar question that was asked before, I've written a more custom format time function:

enum TimeFormat {
    FORMAT_HOURS   = 1 << 0,
    FORMAT_MINUTES = 1 << 1,
    FORMAT_SECONDS = 1 << 2,

func format_time(time, format = FORMAT_DEFAULT, digit_format = "%02d"):
    var digits = []

    if format & FORMAT_HOURS:
        var hours = digit_format % [time / 3600]

    if format & FORMAT_MINUTES:
        var minutes = digit_format % [time / 60]

    if format & FORMAT_SECONDS:
        var seconds = digit_format % [int(ceil(time)) % 60]

    var formatted = String()
    var colon = " : "

    for digit in digits:
        formatted += digit + colon

    if not formatted.empty():
        formatted = formatted.rstrip(colon)

    return formatted

Where time is in seconds, format can have any combination of values from TimeFormat enum, and digit_format is a default string format for time digits. Returns formatted string time. For instance:

var time = format_time(469, FORMAT_MINUTES | FORMAT_SECONDS)
answered Sep 7, 2018 by Xrayez (1,183 points)
selected Sep 7, 2018 by Diet Estus

Thanks! But maybe rstrip() has been removed in Godot 3?

Was it even present in Godot 2? I'm running 3.1.dev.cfcb6e1 (custom build)

This format_time method could be optimized without the use of rstrip though, just don't add the last colon... figured this should work:

for idx in digits.size():
    formatted += digits[idx]
    if idx != digits.size() - 1:
        formatted += colon

Got it, thanks again! I've never used Godot 2, just noticed it wasn't in Godot 3.0. Have yet to play with 3.1 alpha.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.