DEV Community

ksupdev
ksupdev

Posted on

[KONG] Example get local Datetime

#go

Golang code



package utils
// Create Interface
type DateTimeUtils interface {
    GetCurrentDateTimeAsDefaultFormat() string
}

import (
    "time"
    _ "time/tzdata"
)

type dateTimeUtil struct {
    Lc time.Location
}
// Implement Interface
func NewDateTimeUtil() DateTimeUtils {
    locat, error := time.LoadLocation("Asia/Bangkok")

    if error != nil {
        panic(error)
    }

    return &dateTimeUtil{Lc: *locat}
}

func (dt *dateTimeUtil) GetCurrentDateTimeAsDefaultFormat() string {
    currentTime := time.Now().In(&dt.Lc)
    return currentTime.Format("2006/01/02 15:04:05.000000")
}

// Create Test Method

func TestGetCurrentDateTimeAsDefaultFormat(t *testing.T) {
    var ins DateTimeUtils = NewDateTimeUtil()
    toDay := ins.GetCurrentDateTimeAsDefaultFormat()
    if len(strings.TrimSpace(toDay)) == 0 {
        t.Error("Error: get current datetime")

    } else {
        msg := fmt.Sprintf("success: current date time  %v", toDay)
        t.Logf(msg)
    }
}

Enter fullscreen mode Exit fullscreen mode

ทำการ run test

go test -v -run TestGetCurrentDateTimeAsDefaultFormat 
=== RUN   TestGetCurrentDateTimeAsDefaultFormat
    datetime_util_test.go:17: success: current date time  2021/11/01 13:25:52.404100
--- PASS: TestGetCurrentDateTimeAsDefaultFormat (0.00s)
PASS
ok      ananda.co.th/service/units-service/pkg/utils    0.204s
Enter fullscreen mode Exit fullscreen mode

ในส่วนของการ format จะมีตาม list ด้านล่างนี้

Image description

Docker file

FROM golang:alpine as build
WORKDIR /app
ADD . .
RUN CGO_ENABLED=0 GOOS=linux go build -o demo

FROM scratch as final
COPY --from=build /app/demo .
ENV TZ=Asia/Bangkok
CMD ["/demo"]
Enter fullscreen mode Exit fullscreen mode

โดยในส่วนของ ENV TZ=Asia/Bangkok เราสามารถไปหาได้จาก link นะครับ ซึ่งจะมีลักษณะเหมือนด้านล่างนะครับ

Image description

Time zone list

credit by
https://golang.cafe/blog/golang-time-format-example.html
https://www.somkiat.cc/golang-timezone-with-docker/

Top comments (0)