Go time.Parse invalid ISO date

王林
Release: 2024-02-08 21:03:09
forward
417 people have browsed it

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)
}
Copy after login

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

2023-06-06 07:04:58.278 -0700 -0700
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!