简体   繁体   中英

How to parse a date string in a foreign language with go time

So my problem is: I want to do this:

datestring := "19. april 2018"

parsedDate, err := time.Parse("2. January 2006", datestring)
if err != nil {
    fmt.Println(err)
}

fmt.Println(parsedDate)

This snippet works perfectly... but now my input datestring isn't english... it's german. So april fooled me. (German April = English April). Running this with datestring := "19. Februar 2018" fails:

parsing time "12. februar 2018" as "2. January 2006": 
    cannot parse "februar 2018" as "Januar\"

Is there any way to add parseable (natural) languages? Or define the language I expect. I didn't find any mention of this in the documentation.

Thanks!

I believe what you are trying to achieve can be accomplished using the package

https://godoc.org/github.com/goodsign/monday

It allows you to specify that you want to parse the date in the German locale using the ParseInLocation function.

A good example on how to use this (and in german) can be seen in this question .

One way is to convert month in original string from your locale into number or english locale before sending it to Parse() function. It will definitely work.

Here's a yaml-file with definitions for many languages - https://github.com/scrapinghub/dateparser/blob/8e91eb1a6d161a50b1869408c559dc605ef3583f/data/languages.yaml#L116

That's a library in python, so it won't fit go. But you can use this yaml-file for your conversion. It's taken from this answer - https://stackoverflow.com/a/32482516/801426

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM