0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GoでWebAPIを使って現在時刻を取得する

Posted at

この記事は「大分高専 Advent Calendar 2024」10日目の記事です.

はじめに

GoでAPIを作っている時に,現在の日時を取得する必要があったので,実装してみました.現在の日時の取得にはIchigoJam + MixJuice用 日付&時間データというAPIを使用しました.

GoのNow関数

実は,Goのtimeパッケージの中に現在時刻を取得できる関数があります.
time package func Now

time.go
package main
import (
	"fmt"
	"time"
)
func main() {
	now := time.Now()
	fmt.Println("NOW : ", now)
}

出力は以下の通り.

$ go run time.go
NOW : 2024-12-09 21:55:11.078017 +0900 JST m=+0.000137959

日付と時間が取得できました.
しかし,今回は曜日の要素まで一緒に取得したかったのと,秒数まで細かく取得する必要はなかったので,

この記事を参考に,一番シンプルでデータが扱いやすそうな方法を選びました.

実装

日付も時間もまとめて取得できる http://www.openspc2.org/data/date/full.txtというURLを使用しました.

main.go
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

func get_data() string {
	date_url := "http://www.openspc2.org/data/date/full.txt"

	resp, _ := http.Get(date_url)
	// Getリクエストを送る
	defer resp.Body.Close()

	byteArray, _ := ioutil.ReadAll(resp.Body)
	mozi := strings.Fields(string(byteArray))
	var toInt int
	toInt, _ = strconv.Atoi(mozi[3])

	switch toInt {
	// 曜日を漢字に変換
	// goのswitch文ってbreak要らないらしい
	case 0:
		mozi[3] = "日"
	case 1:
		mozi[3] = "月"
	case 2:
		mozi[3] = "火"
	case 3:
		mozi[3] = "水"
	case 4:
		mozi[3] = "木"
	case 5:
		mozi[3] = "金"
	case 6:
		mozi[3] = "土"
	default:
		mozi[3] = "休"
	}
	var content string
	add_content := [7]string{"/", "/", "(", ")", ":", "", ""}
	for i := 0; i < len(mozi); i++ {
		content = content + mozi[i] + add_content[i]
		//文字列の結合
	}
	return content
}
func main() {
	now := get_data()
	fmt.Println("NOW :", now)
}

出力は以下の通り.

$ go run main.go
NOW : 2024/12/9()22:10

おわりに

GoでWebAPIを使って現在日時を取得しました.
GoのNow関数でも現在日時を取得できるので,少し遠回りをしてるような感じがしますが,こういう方法もあるんだくらいに思って欲しいです.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?