HOWTO · Go

Go의 시간 기간

GoLang의 시간 라이브러리는 시간을 여러 형식으로 변환할 수 있는 많은 기능을 제공합니다.

이 페이지의 내용

Go기간 변환은 여러 가지 방법으로 수행할 수 있습니다. time 라이브러리 및 time.duration 메서드는 시간을 계산하고 표시하는 데 자주 사용됩니다.

Duration은 두 개의 정의된 시간 객체 사이에 경과된 시간을 int64 nanosecond 카운트로 나타냅니다.

기간 인스턴스 변환

나노초 1
마이크로초 1000 * 나노초
밀리초 1000 * 마이크로초
두번째 1000 * 밀리초
60 * 초
시간 60 * 분

time.duration 방법 사용

package main

import (
	"fmt"
	"time"
)

func main() {
	d, err := time.ParseDuration("1h25m10.9183256645s")
	if err != nil {
		panic(err)
	}

	count := []time.Duration{
		time.Nanosecond,
		time.Microsecond,
		time.Millisecond,
		time.Second,
		2 * time.Second,
		time.Minute,
		10 * time.Minute,
		time.Hour,
	}

	for _, r := range count {
		fmt.Printf("(%6s) = %s\n", r, d.Round(r).String())
	}
}

출력:

(   1ns) = 1h25m10.918325664s
(   1µs) = 1h25m10.918326s
(   1ms) = 1h25m10.918s
(    1s) = 1h25m11s
(    2s) = 1h25m10s
(  1m0s) = 1h25m0s
( 10m0s) = 1h30m0s
(1h0m0s) = 1h0m0s

위의 코드를 사용하면 모든 해당 기간을 부동 소수점 정수로 계산할 수 있습니다.

time 라이브러리를 사용하여 경과 시간 계산

package main
import (
    "fmt"
    "time"
)
func main() {

    var t time.Duration = 100000000000000
    fmt.Println(t.Hours())
    fmt.Println(t.Minutes())
    fmt.Println(t.Seconds())

    now := time.Now()
    time.Sleep(100000)
    diff := now.Sub(time.Now())

    fmt.Println("Elapsed time in seconds: ", diff.Seconds())
}

출력:

27.77777777777778
1666.6666666666667
100000
Elapsed time in seconds:  -0.0001

경과 시간은 프로세서가 지속 시간을 계산하는 데 걸린 시간을 알려줍니다.

Go에서 시간 기간을 숫자로 변환

package main
import (
    "fmt"

    "time"
)
func main() {

timeInput := 3600

data := time.Duration(timeInput) * time.Millisecond

fmt.Println("The time in Nanoseconds:", int64(data/time.Nanosecond))

fmt.Println("The time in Microseconds:", int64(data/time.Microsecond))

fmt.Println("The time in Milliseconds:", int64(data/time.Millisecond))
}

출력:

The time in Nanoseconds: 3600000000
The time in Microseconds: 3600000
The time in Milliseconds: 3600

위의 코드를 사용하면 숫자를 시간 인스턴스로 변환한 다음 time.Duration이 시간 변환을 수행할 수 있습니다. 결국 시간 인스턴스는 다시 숫자로 변환됩니다.