본문 바로가기
Golang

Golang Time

by 시바도지 2022. 9. 13.
반응형

time 패키지 사용 예시는 다음의 코드와 같다.

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
}

// result: 2009-11-10 23:00:00

 

뿐만 아니라 아래의 코드와 같이 사용이 가능하다.

 

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(time.Now().Format("2006년01월02일 15시04분05초"))
}

 

결과

2009년11월10일 23시00분00초

재밌다.

 

 

time 패키지를 사용하다 보면 의문점이 있을 것이다.

`2006-01-02 15:04:05`

이것은 어떤 의미 또는 연관이 있을까...?

 

날짜 포맷이 기념일이나 무작위 등 인줄 알았으나

인터넷을 뒤적이며 찾아보니 충격적이게도 다음과 같았다...

 

Mon Jan 2 15:04:05 -0700 MST 2006
0   1   2  3  4  5              6

 

 

충격...

 

 

 

time 패키지를 사용한 예제


현재 시간에서 시, 분을 차감해보자.

import (
  "time"
)

func main() {
	now := time.Now()

	convMinutes, _ := time.ParseDuration("10m")
	convHours, _ := time.ParseDuration("1h")
	diffMinutes := now.Add(-convMinutes).Format("2006-01-02 15:04:05")
	diffHours := now.Add(-convHours).Format("2006-01-02 15:04:05")
	
	fmt.Println(now)
	fmt.Println(diffMinutes)
	fmt.Println(diffHours)
}

// 결과
// 2018-12-19 20:52:35.100418 +0900 KST m=+0.000385834
// 2018-12-19 20:42:35
// 2018-12-19 19:52:35

 

현재 날짜에서 년, 월, 일을 차감해보자.

import (
  "time"
)

func main() {
	now := time.Now()

	convDays := 1
	convMonths := 1
	convYears := 1

	diffDays := now.AddDate(0, 0, -convDays).Format("2006-01-02 15:04:05")
	diffMonths := now.AddDate(0, -convMonths, 0).Format("2006-01-02 15:04:05")
	diffYears := now.AddDate(-convYears, 0, 0).Format("2006-01-02 15:04:05")

	fmt.Println(now)
	fmt.Println(diffDays)
	fmt.Println(diffMonths)
	fmt.Println(diffYears)
}

// 결과
// 2018-12-19 21:00:23.506858 +0900 KST m=+0.000362007
// 2018-12-18 21:00:23
// 2018-11-19 21:00:23
// 2017-12-19 21:00:23

 

 

String으로 된 time을 사용한 예제


exampleTime := "2022-08-19 01:55:44" // time을 string으로 받아왔을 경우

date, _ := time.Parse("2006-01-02 15:04:05", exampleTime)

fmt.Println("Year: ", date.Year())   // Year를 추출
fmt.Println("Month: ", date.Month()) // Month를 추출
fmt.Println("Day: ", date.Day())     // Day를 추출

fmt.Println("Year: ", int(date.Year()))   // Year를 추출하여 int로 변환
fmt.Println("Month: ", int(date.Month())) // Month를 추출하여 int로 변환
fmt.Println("Day: ", int(date.Day()))     // Day를 추출하여 int로 변환

 

 

time을 string으로 변환


date_str := date.Format("2006-01-02 15:04:05") // time.time을 string으로 변환

fmt.Println("date_str: ", date_str)
fmt.Println(reflect.TypeOf(date_str)) // type 확인
반응형

'Golang' 카테고리의 다른 글

omitempty  (0) 2023.01.10
Golang 문자열 다루기 (strconv, strings)  (0) 2022.12.10
import 의존성 오류  (0) 2022.06.29
JSON data 사용하기  (0) 2022.04.23
ioutil 패키지를 사용하여 파일 읽기/쓰기  (0) 2022.04.23

댓글