douxiandiyo58855 2018-07-12 18:20
浏览 153
已采纳

使用Go的时间转义数字

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)
  • 写回答

1条回答 默认 最新

  • duanlei0282 2018-07-12 19:14
    关注

    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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100