如何解析非英语字符串中的月份 [英] How to parse month in go from non-english String with

查看:43
本文介绍了如何解析非英语字符串中的月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下字符串解析为一个日期:

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

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

我遵循了,蒙山:

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.

我的问题:我想解析德语字符串.喜欢:

"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?

推荐答案

时间包目前不支持i18n.等待发生这种情况时,您可以尝试使用包装程序包,例如:

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

monday 的文档所述:

星期一不能替代标准时间套餐.这是在国际化功能尚未准备就绪时使用的临时解决方案.

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

这就是为什么星期一不创建任何其他解析算法,布局标识符的原因.它只是time.Format和time.ParseInLocation的包装,并使用所有相同的布局ID,常量等.

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.

这是您使用星期一的示例:

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)
}

输出:

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

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

这篇关于如何解析非英语字符串中的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆