Home > Blockchain >  Work out if 2022-01-14T20:56:55Z is a valid date time in Go
Work out if 2022-01-14T20:56:55Z is a valid date time in Go

Time:05-12

I am attempting to create a function that tells me if a timestamp is valid or not.

My function looks like

// IsTimestamp checks if a string contains a timestamp.
func IsTimestamp(str string) bool {
    _, err := time.Parse("2006-01-02 15:04:05.999", str)
    if err != nil {
        return false
    }

    return true
}

However, passing in 2022-01-14T20:56:55Z returns false when is it a valid timestamp.

I'm thinking this might be something to do with the layout I am using in time.Parse but I've tried just using the date with no luck.

CodePudding user response:

Your format doesn't match your input string, so it's expected that it isn't parsed successfully.

The docs say:

Parse parses a formatted string and returns the time value it represents. See the documentation for the constant called Layout to see how to represent the format. The second argument must be parseable using the format string (layout) provided as the first argument.

Therefore, you should use a layout that's matching your input. Below, I am using RFC3339, which is the format of your input string.

if _, err := time.Parse(time.RFC3339, str); err != nil {
    ...
}

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

CodePudding user response:

2022-01-14T20:56:55Z does not match the layout 2006-01-02 15:04:05.999 because:

  • the layout expects a whitespace after day, not T
  • the layout expects exactly three digits for milliseconds (only two are given 55)
  • the layout does not expect the timezone to be specified. Z is not a valid.

You can match 2022-01-14T20:56:55Z with the layout 2006-01-02T15:04:05.99Z, or 2006-01-02T15:04:05Z. Or even better, use The Fool's answer.

  •  Tags:  
  • go
  • Related