将时间字符串类型解析回时间类型时出现错误。

huangapple go评论83阅读模式
英文:

parse time string type back to time type error

问题

package main

import "fmt"
import "time"

func main() {
    source := "2014-04-22 23:41:12.518845115 +0800 CST"
    Form := "2006-01-02 15:04:05.999999999 -0700 MST"
    t, err := time.Parse(Form, source)

    if err == nil {
        fmt.Println(t.String())
    } else {
        fmt.Println(err)
    }
}

错误:parsing time "2014-04-22 23:41:12 +0800 CST": month out of range

我通过 time.Now().String() 获取了 source,但是无法将其转换回去。这段代码有什么问题?

英文:
package main

import "fmt"
import "time"

func main() {
	source := "2014-04-22 23:41:12.518845115 +0800 CST"
	Form := "2014-04-22 23:41:12.518845115 +0800 CST"
	t, err := time.Parse(Form, source)

	if err == nil {
		fmt.Println(t.String())
	} else {
		fmt.Println(err)
	}
}

Error :parsing time "2014-04-22 23:41:12 +0800 CST": month out of range

I get source by time.Now().String(), but I could not convert it back. What's wrong with this piece of code?

答案1

得分: 2

从文档中可以看到:

Parse解析一个格式化的字符串并返回它表示的时间值。布局通过展示参考时间的格式来定义格式

如果Mon Jan 2 15:04:05 -0700 MST 2006是该值,它将被解释为输入格式的示例。然后,相同的解释将应用于输入字符串。预定义的布局ANSIC、UnixDate、RFC3339和其他布局描述了参考时间的标准和便捷表示。有关格式和参考时间定义的更多信息,请参阅ANSIC的文档和此包定义的其他常量的文档。

(我加粗的部分)。

所以你想要的是

Form := "2006-01-02 15:04:05.000000000 -0700 MST"

这是引用中列出的日期以你的输入字符串格式的形式。需要注意的一点是,在我在playground上进行确认时,看起来在05.000000000(秒和秒的小数部分)部分,你需要确保格式字符串中包含与你想要解析的字符串中完全相同数量的小数点

这是一个展示它工作的playground版本:http://play.golang.org/p/dRniJbqgl7

英文:

From the documentation:

> Parse parses a formatted string and returns the time value it
> represents. The layout defines the format by showing how the reference
> time,

>
> Mon Jan 2 15:04:05 -0700 MST 2006 would be interpreted if it were the
>
> value; it serves as an example of the input format. The same
> interpretation will then be made to the input string. Predefined
> layouts ANSIC, UnixDate, RFC3339 and others describe standard and
> convenient representations of the reference time. For more information
> about the formats and the definition of the reference time, see the
> documentation for ANSIC and the other constants defined by this
> package.

(Bolding mine).

So what you want is

Form := "2006-01-02 15:04:05.000000000 -0700 MST"

Which is the date listed in that quote in the format of your input string. One thing to note while I was writing this on the playground to confirm is that it looks like on the part 05.000000000 (the seconds and fractions of seconds) you need the format string to contain exactly as many decimal points as the string you want to parse.

Here's a playground version showing it works: http://play.golang.org/p/dRniJbqgl7

huangapple
  • 本文由 发表于 2014年4月23日 00:02:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/23224576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定