How to remove the dot in the milliseconds value in time.Format

Viewed 906

I want to produce a time with this specific format in Go using the time.Format function:

yyyy_MM_dd_HH_mm_ss_SSS    // SSS == milliseconds

Following the documentation, I got to this point (using stdFracSecond0):

format := "2006_01_02_15_04_05_.000"
fmt.Println(time.Now().Format(format))

Which outputs:

2021_06_18_10_21_19_.179    

How can I remove the dot before the milliseconds value?

This does not work (millis are always zero):

format := "2006_01_02_15_04_05_000"

Playground example

3 Answers

To remove the dot before milliseconds use strings.Replace() method .Please find the code below with the same logic .

package main

import (
    "fmt"
    "strings"
    "time"
)

func main() {

    format := "2006_01_02_15_04_05_.000"
    fmt.Println(time.Now().Format(format))
    fmt.Println(strings.Replace(time.Now().Format(format), "_.", "_", 1))

}

Output:

2009_11_10_23_00_00_.000
2009_11_10_23_00_00_000

Simply use strings.Replace() to remove . from your formatted time string.

strings.Replace(time.Now().Format(format), `.`, ``, 1)

run here

do function efficiently removes the . (dot) from the format.

As per the format's convention, a decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. Hence, using the same is safe (eg. .000 instead of .999).

The do function does some sanity check so that format is not valid.

package main

import (
    "errors"
    "fmt"
    "os"
    "strings"
    "time"
)

// do replaces the dot (.) with underscore (_) safely
func do(t string) (string, error) {
    // size is the expected length of the string
    const size = 24
    if tLen := len(t); tLen != size {
        return "",
            fmt.Errorf(
                "invalid format size: expected %d, got %d", size, tLen,
            )
    }

    if t[size-4] != '.' {
        return "", errors.New("invalid format")
    }

    // Use strings.Builder for concatenation
    sb := strings.Builder{}
    sb.Grow(size)
    // For: "2006_01_02_15_04_05_.000"
    // Join "2006_01_02_15_04_05_" and "000"
    sb.WriteString(t[0 : size-4])
    sb.WriteString(t[size-3 : size])

    return sb.String(), nil
}

func main() {
    format := "2006_01_02_15_04_05_.000"
    t, err := do(time.Now().Format(format))
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Println(t)
}
Related