Michael0x2a
Michael0x2a

Reputation: 63998

Escaping numbers when using Go's time.Format

I'm currently trying to take a time.Time object and go and produce a formatted string that happens to include some numbers that I do NOT want to be parsed as a time. For example, consider the following program:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    msg := now.Format("Encountered a 502 error on 2006-01-02 15:02 MST") 
    fmt.Println(msg)
}

Unfortunately, the text "502" is interpreted as a time here: running this code will produce output like Encountered a 1112 error on 2018-07-12 9:12 UTC.

Is there any way to escape the 502 numbers so they aren't interpreted as numbers? E.g. similar to how you can escape the % meta-character by using %% in languages that implement strftime-style formatting logic?

Or is my only option to just split this up and use two formatting operations instead of one?

nowString := now.Format("2006-01-02 15:02 MST")
msg := fmt.Sprintf("Encountered 502 error on %s", nowString)

Upvotes: 3

Views: 975

Answers (1)

JimB
JimB

Reputation: 109331

No, there is no escape for numbers in time.Format. The purpose of that method is for formatting time, not for formatting strings in general.

If this is used from multiple locations, the usual solution would be to make a simple function to do the formatting

func nowMessage(msg string) string {
    const layout = "2006-01-02 15:02 MST"
    return fmt.Sprintf("%s %s", msg, time.Now().Format(layout))
}

Upvotes: 1

Related Questions