상세 컨텐츠

본문 제목

[Golang]time.Time 구조체 기본값은 무엇일까요

Golang

by stayhungri 2022. 7. 8. 13:11

본문

이런 질문에 대해 해소를 해보려고 합니다.

- time.Time{} 선언된 변수의 기본 값을 무엇일까요?

- time.Time{} 선언된 변수에 날짜와 시간이 할당 되었는지 안 되었는지 어떻게 알 수 있을까요?

- API 개발 중 날짜와 시간 파라미터를 request body 로 넘기도록 하고 time.Time 으로 받도록 개발했습니다. client 쪽에서 날짜와 시간을 넘겨줬는지 안했는지 어떻게 알 수 있을까요?

 

time.Time 구조체를 보면  날짜와 시간에 대한 값을 저장하기 위해 wall, ext 변수를 활용하고 있습니다. uint64와  int64 는 선언만 하면 기본값으로 0을 가지기 때문에 내부적으로 0 값을 가집니다.

type Time struct {
	// wall and ext encode the wall time seconds, wall time nanoseconds,
	// and optional monotonic clock reading in nanoseconds.
	//
	// From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
	// a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
	// The nanoseconds field is in the range [0, 999999999].
	// If the hasMonotonic bit is 0, then the 33-bit field must be zero
	// and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
	// If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
	// unsigned wall seconds since Jan 1 year 1885, and ext holds a
	// signed 64-bit monotonic clock reading, nanoseconds since process start.
	wall uint64
	ext  int64

	// loc specifies the Location that should be used to
	// determine the minute, hour, month, day, and year
	// that correspond to this Time.
	// The nil location means UTC.
	// All UTC times are represented with loc==nil, never loc==&utcLoc.
	loc *Location
}

 

하지만 선언만 하고 출력을 하면 "0001-01-01 00:00:00 +0000 UTC1" 라고 나옵니다. 그 이유는 String() 함수에서 기본 형식으로 컨버팅을 하는데 그 중간에 할당해 주기 때문입니다. 

func (t Time) String() string {
	s := t.Format("2006-01-02 15:04:05.999999999 -0700 MST")

	// Format monotonic clock reading as m=±ddd.nnnnnnnnn.
	if t.wall&hasMonotonic != 0 {  // t.wall 이 0 이라 아래 로직은 수행 아됨

	...
    
	return s
}

 

그럼 기본 값인지 아닌지는 어떻게 알 수 있을까요? time.Time 멤버 함수로 제공하는 IsZero() 를 이용하면 됩니다.

// IsZero reports whether t represents the zero time instant,
// January 1, year 1, 00:00:00 UTC.
func (t Time) IsZero() bool {
   return t.sec() == 0 && t.nsec() == 0
}
func isZero() {
   var t time.Time

   fmt.Printf("t: %+v / %t", t, t.IsZero())
}

// output
t: 0001-01-01 00:00:00 +0000 UTC / true

 

관련글 더보기