Home >Backend Development >Golang >Go time.Parse invalid ISO date

Go time.Parse invalid ISO date

王林
王林forward
2024-02-08 21:03:09475browse

Go time.Parse 无效的 ISO 日期

Question content

Is there any way to use time.Parse to parse the following date string:

2023-06-06T07:04:58:278-07?

I tried using the format 2006-01-02T15:04:05:000Z07, but the last : caused an error.

https://go.dev/play/p/y4T7meCX6D5


Correct answer


Write time.parse wrapper function to accept A decimal point, decimal comma, or colon as the seconds decimal separator.

package main

import (
    "fmt"
    "strings"
    "time"
)

// accept a decimal point, decimal comma, or colon
// as the seconds decimal separator.
func timeparse(layout, value string) (time.time, error) {
    t, err := time.parse(layout, value)
    if err == nil {
        return t, err
    }
    if strings.count(value, ":") != 3 {
        return t, err
    }
    i := strings.lastindexbyte(value, ':')
    if i < 0 {
        return t, err
    }
    value2 := value[:i] + "." + value[i+1:]
    t2, err2 := time.parse(layout, value2)
    if err2 == nil {
        return t2, err2
    }
    return t, err
}

func main() {
    indate := "2023-06-06t07:04:58:278-07"
    parseformat := "2006-01-02t15:04:05z07"
    t, e := timeparse(parseformat, indate)
    if e != nil {
        fmt.println(e)
    }
    fmt.println(t)
}

https://www.php.cn/link/a933075894d2fccffdaa2a492a4a12da

2023-06-06 07:04:58.278 -0700 -0700

The above is the detailed content of Go time.Parse invalid ISO date. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Unable to open file nameNext article:Unable to open file name