在Go语言中,`time.Time`的`zero`值是`0001-01-01 00:00:00 +0000 UTC`。

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

What is the `zero` value for time.Time in Go?

问题

time.Time 的零值是 0001-01-01 00:00:00 +0000 UTC

英文:

In an error condition, I tried to return nil, which throws the error:

cannot use nil as type time.Time in return argument

What is the zero value for time.Time?

答案1

得分: 435

你应该使用Time.IsZero()函数:

func (Time) IsZero

或者

func (t Time) IsZero() bool

IsZero函数用于判断t是否表示零时间点,即公元1年1月1日00:00:00 UTC。

英文:

You should use the Time.IsZero() function instead:

func (Time) IsZero

or

func (t Time) IsZero() bool

> IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.

答案2

得分: 284

调用一个空的time.Time结构字面量将返回Go语言的零日期。因此,对于以下的打印语句:

fmt.Println(time.Time{})

输出结果为:

0001-01-01 00:00:00 +0000 UTC

为了完整起见,官方文档明确说明:

> Time类型的零值是UTC时区的公元1年1月1日 00:00:00.000000000。

英文:

Invoking an empty time.Time struct literal will return Go's zero date. Thus, for the following print statement:

fmt.Println(time.Time{})

The output is:

0001-01-01 00:00:00 +0000 UTC

For the sake of completeness, the official documentation explicitly states:

> The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

答案3

得分: 7

time.Time 的零值是 0001-01-01 00:00:00 +0000 UTC。请参考 http://play.golang.org/p/vTidOlmb9P

英文:

The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC See http://play.golang.org/p/vTidOlmb9P

答案4

得分: 3

在Go v1.18上进行了测试

time.Time 的默认值是:

0001-01-01 00:00:00 +0000 UTC

使用 IsZero() 函数进行检查是一种简洁的方式。

var zeroTime time.Time

if zeroTime.IsZero() {
    // 当为零时执行某些操作
}

英文:

Tested on Go v1.18

The default value for time.Time is:

0001-01-01 00:00:00 +0000 UTC

Checking with IsZero() function is a clean way.

var zeroTime time.Time

if zeroTime.IsZero() {
    // do something when zero
}

huangapple
  • 本文由 发表于 2014年4月14日 12:29:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/23051973.html
匿名

发表评论

匿名网友

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

确定