+1 vote

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?

in Engine by (1,533 points)
edited by

1 Answer

+2 votes
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)
by (1,344 points)
selected by

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.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.