Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 676
Michael0x2a Avatar asked Dec 06 '25 05:12

Michael0x2a


1 Answers

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))
}
like image 186
JimB Avatar answered Dec 08 '25 19:12

JimB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!