dtsnx44260 2014-02-11 08:30
浏览 53
已采纳

如何解析非英语字符串中的月份

I want to parse the following string to a date in go:

"This item will be released on March 9, 2014."

I followed this and came up whith:

func findReleaseDateString(raw string) time.Time {
  test, err := time.Parse("This item will be released on January 2, 2006.", raw)
  if err != nil {
      panic(err)
  }

 return test
}

Which works like a charm for english strings.

My problem: I would like to parse german strings. Like:

"Dieser Artikel wird am 9. März 2014 erscheinen."

I am aware, that I could match day, month and year via a regex and then parse it. But is there any possibility to tell time.Parse to use a different set of constants for month?

  • 写回答

2条回答 默认 最新

  • douhanshu5517 2014-02-11 08:56
    关注

    There is currently no i18n support for the time package. While waiting for that to happen, you can try using a wrapper package such as:

    github.com/goodsign/monday

    As stated by monday's documentation:

    Monday is not an alternative to standard time package. It is a temporary solution to use while the internationalization features are not ready.

    That's why monday doesn't create any additional parsing algorithms, layout identifiers. It is just a wrapper for time.Format and time.ParseInLocation and uses all the same layout IDs, constants, etc.

    Here is your example using monday:

    package main
    
    import (
        "fmt"
        "github.com/goodsign/monday"
        "time"
    )
    
    func findReleaseDateString(raw string) time.Time {
        loc, _ := time.LoadLocation("Europe/Berlin")
        t, err := monday.ParseInLocation("Dieser Artikel wird am 2. January 2006 erscheinen.", raw, loc, monday.LocaleDeDE)
        if err != nil {
            panic(err)
        }
    
        return t
    }
    
    func main() {
        t := findReleaseDateString("Dieser Artikel wird am 9. März 2014 erscheinen.")
        fmt.Println(t)
    }
    

    Output:

    2014-03-09 00:00:00 +0100 CET

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵