Home > Enterprise >  How to convert millisecond (uint64) into HH:MM:SS,MMM format in Go
How to convert millisecond (uint64) into HH:MM:SS,MMM format in Go

Time:06-15

In this scenario, the uint64 value does not specify a specific date.
I'm using uint64 to show a specific point of a video in milliseconds.
As in the title I need to convert this integer value. I think solving this using simple math would cause problems (rounding etc.).

Below is an example for the scenario:

Point 60104: Reference to 0th hour, 1st minute, 0th second and 104th millisecond.

package main

import "fmt"
// maybe time...

func main() {
    videoPoint := uint64(65104)

    // I want 00:01:05,104
    strVideoPoint := ToReadablePoint(videoPoint)
    fmt.Println(strVideoPoint)
}

func ToReadablePoint(point uint64) string {
    // algorithm will be written here
    return ""
}

I used Go but you can also write the algorithm in C/C . The key here is algorithm.

CodePudding user response:

Using the time package

If the duration is less than a day, you may simply add it to a reference timestamp having zero time part, then format the time using a proper layout.

The reference time may be the zero value of time.Time or the unix reference time.

For example:

ms := int64(65104)

var t time.Time // Zero time
t = t.Add(time.Duration(ms) * time.Millisecond)
fmt.Println(t.Format("15:04:05,000"))

t = time.UnixMilli(ms)
fmt.Println(t.Format("15:04:05,000"))

This will output (try it on the Go Playground):

00:01:05,104
00:01:05,104

If you want to handle durations bigger than a day, this solution is not suitable. A possible solution is to calculate hours yourself, and use the above method for the rest (minutes, seconds, milliseconds).

For example:

const msInHour = 60 * 60 * 1000

func format(ms int64) string {
    hours := ms / msInHour
    ms = ms % msInHour
    t := time.UnixMilli(ms)
    return fmt.Sprintf("d:%s", hours, t.Format("04:05,000"))
}

Testing it:

fmt.Println(format(65104))
fmt.Println(format(27*60*60*1000   65104))

This will output (try it on the Go Playground):

00:01:05,104
27:01:05,104

Rolling your own solution

If you don't want to use the time package, you can do it yourself. The algorithm is simply divisions and remainers. E.g. the millisecond part is the remainder after dividing by 1000. The seconds after this is the remainder after dividing by 60 etc.

For example:

func format(n int64) string {
    ms := n % 1000
    n /= 1000
    sec := n % 60
    n /= 60
    min := n % 60
    n = n / 60
    return fmt.Sprintf("d:d:d,d", n, min, sec, ms)
}

This also handles durations greater than a day. Testing it:

fmt.Println(format(65104))
fmt.Println(format(27*60*60*1000   65104))

This will output (try it on the Go Playground):

00:01:05,104
27:01:05,104
  • Related