Go에서 다른 시간대 작업

Go에서 다른 시간대 작업

시간대는 날짜와 시간을 다루는 모든 애플리케이션에 매우 중요합니다. 물론 이것은 대륙과 위치에 걸쳐 사용자에게 서비스를 제공하는 앱의 경우 특히 그렇습니다. 표준 시간대는 전 세계 특정 위치에 대한 UTC(Coordinated Universal Time)의 오프셋을 결정합니다. 정확하고 신뢰할 수 있는 시간 처리를 보장하는 데 중요한 역할을 합니다.

Go는 표준 라이브러리에서 시간 및 시간대 작업을 위한 시간 패키지를 제공합니다. time 패키지를 사용하여 다양한 위치에서 시간대를 가져오고 변환할 수 있습니다.

더 타임 패키지

시간 패키지 는 시간 및 날짜 작업, 시간 측정 및 표시, 윤초 없이 그레고리력을 사용하여 날짜 조작을 위한 기능을 제공합니다.

time 패키지는 시간대를 설정하는 데 사용할 수 있는 위치 필드가 포함된 Time 구조체 유형을 제공합니다.

import 문을 사용하여 시간 패키지를 가져올 수 있습니다.

import "time"

다음은 시간 구조체 유형과 해당 필드입니다. 필드는 내보내지지 않으므로 공식 문서에는 없습니다.

package main

type Time struct {
    // wall is the wall time in the format returned by the runtime.nanotime()
    // function.
    wall uint64

    // ext is the monotonic clock reading in the format returned by
    // runtime.nanotime().
    ext int64

    // loc is a pointer to the Location struct associated with this time.
    loc *Location
}

type Location struct {
    // name is the time zone name, such as "UTC"or "PST".
    name string

    // zone contains information about the time zone abbreviation, offset,
    // and rule for a single time zone in the location.
    zone []zone

    // tx contains information about when the time zone abbreviation or
    // offset changes for a location.
    tx []zoneTrans

    // extend contains the name of a parent time zone if this location
    // extends from another one.
    extend string

    // cacheStart and cacheEnd are Unix timestamps that deine the range
    // for which the cacheZone field is valid.
    cacheStart int64
    cacheEnd int64

    // cacheZone points to the zone that is currently valid for the time
    // range defined by cacheStart and cacheEnd.
    cacheZone *zone
}

시간대 메서드를 포함하여 많은 메서드가 Time 및 Location 구조체를 사용합니다.

시간대 정보 로드 중

시간대 정보 로드는 시간대 작업 시 기본 작업 중 하나입니다. LoadLocation 메서드는 IANA 시간대 데이터베이스 에서 시간대 정보를 로드하는 기능을 제공 합니다 . LoadLocation 메서드 는 시간대 이름을 받아 처리를 위해 위치 정보와 오류를 반환합니다. 시간대 정보를 로드하면 시간대 와 연결된 시간 구조 인스턴스를 생성합니다.

import (
    "fmt"
    "time"
)

func main() {
    // Load the time zone location for America/New_York
    loc, err: = time.LoadLocation("America/New_York")

    if err! = nil {
        fmt.Println("Error loading location:", err)
        return
    }

    // Get the current time at a location
    now: = time.Now().In(loc)
    fmt.Println("Current time in New York:", now)
}

Now 함수 의 In 메서드는 위치를 가져와 거기에 시간을 인쇄합니다.

NY의 현재 시간을 출력한 결과

또한 위치 문자열과 UTC에서 표준 시간대 오프셋을 알고 있는 경우 FixedZone 메서드를 사용하여 위치의 현재 시간을 로드할 수 있습니다. 먼저 현재 시간을 UTC로 로드한 다음 FixedZone 메서드를 사용하여 위치를 시간 인스턴스의 In the 메서드에 전달하기 전에 문자열 및 오프셋을 기반으로 위치를 로드합니다.

import (
    "fmt"
    "time"
)

func main() {
    // Get the current time in UTC
    now: = time.Now().UTC()

    // Set the time zone for Lagos
    lagos: = now.In(time.FixedZone("WAT", 3600))

    // Print the current time in both locations
    fmt.Println("Current time in Lagos:", lagos)
}

main 함수 는 Lagos의 현재 시간을 콘솔에 인쇄합니다.

시간대 기간 측정

time 패키지는 time.Time 값 과 관련된 표준 시간대의 약어 및 오프셋을 검색하기 위한 Zone 메서드를 제공합니다. Zone 메소드는 시간대의 약어(예: “America/New_York”의 경우 “EST”)를 나타내는 문자열과 UTC 동쪽의 초를 나타내는 정수를 반환합니다.

import (
    "fmt"
    "time"
)

func main() {
    // Load the time zone location for America/New_York
    loc, err: = time.LoadLocation("America/New_York")

    if err! = nil {
        fmt.Println("Error loading location:", err)
        return
    }

    // Get the current time in UTC and the specified location
    t1: = time.Now()
    t2: = t1.In(loc)

    // Get the offset in seconds for each time zone
    //for the time zones
    _, offset1: = t1.Zone()
    _, offset2: = t2.Zone()

    // Calculate the duration of the time zone shift
    // between UTC and America/New_York
    duration: = offset2 - offset1

    fmt.Printf("The time zone shift duration" +
      "between UTC and New York is: %d seconds", duration)
}

main 함수에서 Zone 메서드는 두 시간대(time.Time 값) 사이의 시간대 이동 기간을 측정합니다. t1 변수는 UTC의 현재 시간이고 t2 변수 는 “America/New_York” 시간대의 현재 시간입니다.

이 함수는 시간대 이동을 초 단위로 나타내는 기간 변수(시간대 간 오프셋 차이)를 인쇄합니다.

시간대 사이의 시간 평가

시간대 사이의 기간을 알고 있으면 시간대 사이의 시간을 평가할 수 있습니다. time.Time 구조체 인스턴스의 In 메서드의 Add 메서드를 사용하여 시간대의 시간에 기간을 추가할 수 있습니다.

import (
    "log"
    "time" // import the time package
)

func evaluateTime(t time.Time, duration time.Duration) time.Time {
    // load the location for Africa/Lagos
    location, err: = time.LoadLocation("Africa/Lagos")

    if err! = nil {
        log.Println("There was an error loading the location")
    }

    return t.In(location).Add(duration)
}

evaluateTime 함수는 time.Time 인스턴스와 time.Duration 유형의 기간을 받아 표준 시간대의 시간을 반환합니다. “Africa/Lagos”의 현재 시간을 로드하고 시간에 기간을 추가합니다.

시간 패키지로 시간과 날짜 조작

시간 패키지는 시간과 날짜 모두에 대해 매우 다재다능합니다. time 패키지는 시간을 Unix 시간으로 변환하기 위한 Unix(), 고루틴 일시 중지를 위한 Sleep(), 시간 값을 문자열로 형식화하기 위한 Format()과 같은 함수를 제공합니다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다