time

package
v1.21.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 31, 2023 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

パッケージtimeは時間を測定し表示する機能を提供します。

暦の計算は常にグレゴリオ暦を前提としており、閏秒は考慮しません。

モノトニッククロック

オペレーティングシステムは「壁掛け時計(wall clock)」と「モノトニッククロック(monotonic clock)」の2つを提供しています。壁掛け時計はクロック同期により変更される可能性がありますが、モノトニッククロックは変更されません。一般的なルールは、壁掛け時計は時刻を表示するために使用し、モノトニッククロックは時間を測定するために使用することです。このパッケージでは、time.Nowが返すTimeには壁掛け時計の読み取り結果とモノトニッククロックの読み取り結果の両方が含まれています。後の時刻表示操作は壁掛け時計の読み取り結果を使用し、後の時間測定操作(比較や差分の計算など)はモノトニッククロックの読み取り結果を使用します。

たとえ壁掛け時計が操作中に変更された場合でも、以下のコードは常に約20ミリ秒の経過時間を計算します。

start := time.Now()
... 20ミリ秒かかる処理 ...
t := time.Now()
elapsed := t.Sub(start)

time.Since(start)、time.Until(deadline)、time.Now().Before(deadline)などの他のイディオムも、壁掛け時計のリセットに対して同様に頑健です。

このセクションの残りの部分では、操作がモノトニッククロックを使用する方法の詳細を述べますが、これらの詳細を理解することはこのパッケージの使用には必要ありません。

time.Nowが返すTimeにはモノトニッククロックの読み取り結果が含まれています。Time tがモノトニッククロックの読み取り結果を持つ場合、t.Addは壁掛け時計とモノトニッククロックの読み取り結果の両方に同じ期間を加算して結果を計算します。t.AddDate(y, m, d)、t.Round(d)、t.Truncate(d)は壁掛け時計の計算なので、結果からモノトニッククロックの読み取り結果は常に除去されます。t.In、t.Local、t.UTCは壁掛け時計の解釈への影響のために使用されますが、結果からモノトニッククロックの読み取り結果も常に除去されます。モノトニッククロックの読み取り結果を除去する正確な方法は、t = t.Round(0)を使用することです。

tとuのいずれもモノトニッククロックの読み取り結果を含む場合、t.After(u)、t.Before(u)、t.Equal(u)、t.Compare(u)、t.Sub(u)は壁掛け時計の読み取り結果を無視してモノトニッククロックの読み取り結果だけを使用して実行されます。tまたはuのいずれかがモノトニッククロックの読み取り結果を含まない場合、これらの操作は壁掛け時計の読み取り結果を使用します。

一部のシステムでは、コンピューターがスリープモードに入るとモノトニッククロックが停止することがあります。そのようなシステムでは、t.Sub(u)はtとuの間で経過した実際の時間を正確に反映しない場合があります。

モノトニッククロックの読み取り結果には、現在のプロセスの外部では意味がありません。t.GobEncode、t.MarshalBinary、t.MarshalJSON、t.MarshalTextによって生成されるシリアル化された形式では、モノトニッククロックの読み取り結果は省略され、t.Formatはそれに対するフォーマットを提供しません。同様に、コンストラクタtime.Date、time.Parse、time.ParseInLocation、およびtime.Unix、およびアンマーシャラーt.GobDecode、t.UnmarshalBinary、t.UnmarshalJSON、およびt.UnmarshalTextは常にモノトニッククロックの読み取り結果のない時刻を作成します。

モノトニッククロックの読み取り結果はTimeの値にのみ存在します。Durationの値やt.Unixおよび関連する関数が返すUnix時刻には含まれていません。

Goの==演算子は、時間の瞬間だけでなく、位置情報とモノトニッククロックの読み取り結果も比較します。Time型の等値テストについては、Time型のドキュメントを参照してください。

デバッグのため、t.Stringの結果にはモノトニッククロックの読み取り結果が含まれます(存在する場合)。t != uが異なるモノトニッククロックの読み取り結果によるものであれば、t.String()とu.String()を表示した時にその差が見えます。

Index

Examples

Constants

View Source
const (
	Layout      = "01/02 03:04:05PM '06 -0700"
	ANSIC       = "Mon Jan _2 15:04:05 2006"
	UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
	RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
	RFC822      = "02 Jan 06 15:04 MST"
	RFC822Z     = "02 Jan 06 15:04 -0700"
	RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
	RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
	RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700"
	RFC3339     = "2006-01-02T15:04:05Z07:00"
	RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
	Kitchen     = "3:04PM"
	// 便利なタイムスタンプ。
	Stamp      = "Jan _2 15:04:05"
	StampMilli = "Jan _2 15:04:05.000"
	StampMicro = "Jan _2 15:04:05.000000"
	StampNano  = "Jan _2 15:04:05.000000000"
	DateTime   = "2006-01-02 15:04:05"
	DateOnly   = "2006-01-02"
	TimeOnly   = "15:04:05"
)

これらはTime.Formatとtime.Parseで使用するための事前定義されたレイアウトです。 これらのレイアウトで使用される参照時間は、特定のタイムスタンプです:

01/02 03:04:05PM '06 -0700

(2006年1月2日15時04分05秒、GMTより7時間西のタイムゾーン)。 その値は、以下にリストされている定数であるLayoutとして記録されます。UNIX タイムとしては、1136239445です。MSTはGMT-0700であるため、参照時間は UNIXのdateコマンドで次のように表示されます:

Mon Jan 2 15:04:05 MST 2006

月の数字を日の前に置くアメリカの慣習を採用していることは、歴史的な誤りです。

Time.Formatの例では、レイアウト文字列の動作を詳しく説明しており、参考になります。

RFC822、RFC850、RFC1123のフォーマットは、ローカル時間にのみ適用する必要があります。 UTC時間に適用する場合、時差表示として「UTC」が使用されますが、厳密にはこれらのRFCでは その場合に「GMT」の使用が必要です。 一般に、RFC1123の代わりにRFC1123Zを使用するべきです。 また、新しいプロトコルにはRFC3339を優先すべきです。 RFC3339、RFC822、RFC822Z、RFC1123、RFC1123Zは、フォーマット用途に有用です。 time.Parseで使用する場合、これらはRFCで許可されているすべての時間形式を受け付けず、 正式に定義されていない時間形式を受け入れます。 RFC3339Nano形式は秒の末尾のゼロを削除するため、フォーマット後に正しくソートされない場合があります。

ほとんどのプログラムは、FormatやParseに渡すための定義済みの定数の1つを使用できます。 カスタムレイアウト文字列を作成する場合以外は、このコメントの残りは無視してかまいません。

独自のフォーマットを定義するには、参照時間があなたの方法でどのように フォーマットされるかを書き出してください。ANSIC、StampMicro、Kitchenなどの 定数の値を参照してください。モデルは、参照時間がどのようになっているかを実証し、 FormatとParseメソッドが一般的な時間値に同じ変換を適用できるようにすることです。

以下はレイアウト文字列のコンポーネントの概要です。各要素は参照時間の要素のフォーマットを 例示しています。これらの値のみが認識されます。参照時間の一部として認識されないレイアウト文字列の テキストは、Formatでそのまま出力され、Parseの入力にそのまま表示されると予想されます。

年: "2006" "06" 月: "Jan" "January" "01" "1" 曜日: "Mon" "Monday" 月の日にち: "2" "_2" "02" 年の日にち: "__2" "002" 時: "15" "3" "03" (PMまたはAM) 分: "4" "04" 秒: "5" "05" AM/PMマーク: "PM"

数値のタイムゾーンオフセットは以下のようにフォーマットされます:

"-0700" ±hhmm "-07:00" ±hh:mm "-07" ±hh "-070000" ±hhmmss "-07:00:00" ±hh:mm:ss

フォーマット内の符号をZに置き換えると、UTCゾーンのオフセットではなく ZがプリントされるISO 8601の動作になります。 したがって:

"Z0700" Zまたは±hhmm "Z07:00" Zまたは±hh:mm "Z07" Zまたは±hh "Z070000" Zまたは±hhmmss "Z07:00:00" Zまたは±hh:mm:ss

フォーマット文字列内では、"_2"と"__2"の下線は、次の数字が複数桁である場合に 数字に置き換えられる可能性のあるスペースを表します。 これにより、固定桁のUNIXタイムフォーマットとの互換性が保たれます。先頭のゼロは ゼロパディングされた値を表します。

フォーマット002は空白でパディングされ、ゼロでパディングされた3文字の年の日を表します。 パディングされていない年の日フォーマットはありません。

カンマまたは小数点の後にゼロが1つ以上続く場合、指定した小数桁数で出力される小数秒を表します。 カンマまたは小数点の後に9が1つ以上続く場合、指定した小数桁数で出力され、末尾のゼロは削除されます。 たとえば、「15:04:05,000」または「15:04:05.000」はミリ秒の精度でフォーマットまたは解析します。

いくつかの有効なレイアウトは、space paddingのようなフォーマットやzone情報のZのような フォーマットのため、time.Parseには無効な時間値です。

View Source
const (
	Nanosecond  Duration = 1
	Microsecond          = 1000 * Nanosecond
	Millisecond          = 1000 * Microsecond
	Second               = 1000 * Millisecond
	Minute               = 60 * Second
	Hour                 = 60 * Minute
)

共通の期間です。Dayやそれ以上の単位の定義はありません。 夏時間ゾーンの移行時に混乱を避けるためです。

Durationの単位数を数えるには、次のように割ります:

second := time.Second
fmt.Print(int64(second/time.Millisecond)) // 1000と出力されます

整数の単位数をDurationに変換するには、次のように掛けます:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // 10sと出力されます

Variables

This section is empty.

Functions

func After

func After(d Duration) <-chan Time

durationが経過するのを待って、その後で現在の時刻を返されたチャネルに送信します。 これはNewTimer(d).Cと同等です。 ガベージコレクタによってTimerが回収されるのは、タイマーが発火するまでではありません。 効率が問題の場合は、代わりにNewTimerを使用し、タイマーが不要になった場合はTimer.Stopを呼び出してください。

Example
select {
case m := <-c:
	handle(m)
case <-time.After(10 * time.Second):
	fmt.Println("timed out")
}
Output:

func Sleep

func Sleep(d Duration)

Sleepは現在のゴルーチンを少なくともdの期間だけ一時停止します。 負数またはゼロの期間は、Sleepがすぐに戻る原因となります。

Example
package main

import (
	"github.com/shogo82148/std/time"
)

func main() {
	time.Sleep(100 * time.Millisecond)
}
Output:

func Tick

func Tick(d Duration) <-chan Time

Tickは、ティッキングチャネルにのみアクセスを提供するためのNewTickerの便利なラッパーです。Tickerをシャットダウンする必要のないクライアントに便利ですが、シャットダウンの方法がないため、ガベージコレクタによって元のTickerは回収されません。"リーク"します。 NewTickerとは異なり、d <= 0の場合にはnilが返されます。

Example
c := time.Tick(5 * time.Second)
for next := range c {
	fmt.Printf("%v %s\n", next, statusUpdate())
}
Output:

Types

type Duration

type Duration int64

Durationは2つの瞬間の経過時間をint64ナノ秒カウントとして表します。 この表現は、最大表現可能な期間を約290年に制限しています。

Example
t0 := time.Now()
expensiveCall()
t1 := time.Now()
fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
Output:

func ParseDuration

func ParseDuration(s string) (Duration, error)

ParseDurationは期間文字列を解析します。 期間文字列は、可能性のある符号付きの連続した 小数点数、オプションの小数部および単位接尾辞からなります。 例: "300ms"、"-1.5h"、または "2h45m"。 有効な時間単位は「ns」、「us」(または「µs」)、「ms」、「s」、「m」、「h」です。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	hours, _ := time.ParseDuration("10h")
	complex, _ := time.ParseDuration("1h10m10s")
	micro, _ := time.ParseDuration("1µs")
	// このパッケージでは、マイクロのための誤ったが一般的な接頭辞uも受け入れます。
	micro2, _ := time.ParseDuration("1us")

	fmt.Println(hours)
	fmt.Println(complex)
	fmt.Printf("There are %.0f seconds in %v.\n", complex.Seconds(), complex)
	fmt.Printf("There are %d nanoseconds in %v.\n", micro.Nanoseconds(), micro)
	fmt.Printf("There are %6.2e seconds in %v.\n", micro2.Seconds(), micro)
}
Output:

10h0m0s
1h10m10s
There are 4210 seconds in 1h10m10s.
There are 1000 nanoseconds in 1µs.
There are 1.00e-06 seconds in 1µs.

func Since

func Since(t Time) Duration

Since(t)は、tから経過した時間を返します。 これはtime.Now().Sub(t)の省略形です。

func Until added in v1.8.0

func Until(t Time) Duration

Untilはtまでの時間を返します。 これはt.Sub(time.Now())の省略形です。

func (Duration) Abs added in v1.19.0

func (d Duration) Abs() Duration

Absはdの絶対値を返します。 特別なケースとして、math.MinInt64はmath.MaxInt64に変換されます。

func (Duration) Hours

func (d Duration) Hours() float64

Hoursは時間を浮動小数点数として返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	h, _ := time.ParseDuration("4h30m")
	fmt.Printf("I've got %.1f hours of work left.", h.Hours())
}
Output:

I've got 4.5 hours of work left.

func (Duration) Microseconds added in v1.13.0

func (d Duration) Microseconds() int64

Microsecondsは、整数のマイクロ秒数として期間を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	u, _ := time.ParseDuration("1s")
	fmt.Printf("One second is %d microseconds.\n", u.Microseconds())
}
Output:

One second is 1000000 microseconds.

func (Duration) Milliseconds added in v1.13.0

func (d Duration) Milliseconds() int64

Millisecondsは、期間を整数のミリ秒カウントとして返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	u, _ := time.ParseDuration("1s")
	fmt.Printf("One second is %d milliseconds.\n", u.Milliseconds())
}
Output:

One second is 1000 milliseconds.

func (Duration) Minutes

func (d Duration) Minutes() float64

Minutesは、分単位の浮動小数点数としての期間を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	m, _ := time.ParseDuration("1h30m")
	fmt.Printf("The movie is %.0f minutes long.", m.Minutes())
}
Output:

The movie is 90 minutes long.

func (Duration) Nanoseconds

func (d Duration) Nanoseconds() int64

Nanosecondsは、期間を整数のナノ秒数として返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	u, _ := time.ParseDuration("1µs")
	fmt.Printf("One microsecond is %d nanoseconds.\n", u.Nanoseconds())
}
Output:

One microsecond is 1000 nanoseconds.

func (Duration) Round added in v1.9.0

func (d Duration) Round(m Duration) Duration

Round関数は、dを最も近いmの倍数に丸めた結果を返します。 半分の値の丸め方は、ゼロから離れるように丸めます。 結果がDurationに格納できる最大(または最小)値を超える場合、 Round関数は最大(または最小)のdurationを返します。 m <= 0の場合、Round関数はdをそのまま返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

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

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

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

d.Round(   1ns) = 1h15m30.918273645s
d.Round(   1µs) = 1h15m30.918274s
d.Round(   1ms) = 1h15m30.918s
d.Round(    1s) = 1h15m31s
d.Round(    2s) = 1h15m30s
d.Round(  1m0s) = 1h16m0s
d.Round( 10m0s) = 1h20m0s
d.Round(1h0m0s) = 1h0m0s

func (Duration) Seconds

func (d Duration) Seconds() float64

Secondsは、秒単位の浮動小数点数としての期間を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	m, _ := time.ParseDuration("1m30s")
	fmt.Printf("Take off in t-%.0f seconds.", m.Seconds())
}
Output:

Take off in t-90 seconds.

func (Duration) String

func (d Duration) String() string

Stringは、期間を「72h3m0.5s」という形式の文字列で返します。 先頭のゼロ単位は省略されます。特別なケースとして、1秒未満の期間は、先頭の数字が0以外になるように、より小さな単位(ミリ秒、マイクロ秒、ナノ秒)を使用してフォーマットされます。ゼロ期間は「0s」としてフォーマットされます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	fmt.Println(1*time.Hour + 2*time.Minute + 300*time.Millisecond)
	fmt.Println(300 * time.Millisecond)
}
Output:

1h2m0.3s
300ms

func (Duration) Truncate added in v1.9.0

func (d Duration) Truncate(m Duration) Duration

Truncate は d を 0 に向かって丸めた結果を、m の倍数にして返します。 もし m <= 0 であれば、Truncate は d をそのまま返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

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

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

	for _, t := range trunc {
		fmt.Printf("d.Truncate(%6s) = %s\n", t, d.Truncate(t).String())
	}
}
Output:

d.Truncate(   1ns) = 1h15m30.918273645s
d.Truncate(   1µs) = 1h15m30.918273s
d.Truncate(   1ms) = 1h15m30.918s
d.Truncate(    1s) = 1h15m30s
d.Truncate(    2s) = 1h15m30s
d.Truncate(  1m0s) = 1h15m0s
d.Truncate( 10m0s) = 1h10m0s
d.Truncate(1h0m0s) = 1h0m0s

type Location

type Location struct {
	// contains filtered or unexported fields
}

Locationは時間インスタンスとその時点で使用されているタイムゾーンをマッピングします。 通常、Locationは地理的な範囲で使用されている時間オフセットの集合を表します。 多くの場所では、夏時間が使用されているかどうかによって時間オフセットが異なります。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	// 中国はサマータイムを実施していません。UTCから8時間の固定オフセットを使用しています。
	secondsEastOfUTC := int((8 * time.Hour).Seconds())
	beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)

	// システムにタイムゾーンデータベースが存在する場合、その場所を読み込むことが可能です。例えば:
	//    ニューヨーク、err := time.LoadLocation("America/New_York")

	// 時間の作成には場所が必要です。一般的な場所にはtime.Localとtime.UTCがあります。
	timeInUTC := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
	sameTimeInBeijing := time.Date(2009, 1, 1, 20, 0, 0, 0, beijing)

	// UTCの時計の時間が1200であり、北京の時計の時間が2000であるが、北京は8時間進んでいるため、
	// 実際にはこの2つの日時は同じ瞬間を表しています。
	timesAreEqual := timeInUTC.Equal(sameTimeInBeijing)
	fmt.Println(timesAreEqual)

}
Output:

true
var Local *Location = &localLoc

Local はシステムのローカルなタイムゾーンを表します。 Unix システムでは、Local は TZ 環境変数を参照して使用するタイムゾーンを見つけます。TZ が指定されていない場合は、システムのデフォルトの /etc/localtime を使用します。 TZ="" は UTC を使用します。 TZ="foo" はシステムのタイムゾーンディレクトリ内のファイル foo を使用します。

var UTC *Location = &utcLoc

UTCは協定世界時(UTC)を表します。

func FixedZone

func FixedZone(name string, offset int) *Location

FixedZoneは、常に指定されたタイムゾーン名とオフセット(UTCからの秒数)を使用するLocationを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	loc := time.FixedZone("UTC-8", -8*60*60)
	t := time.Date(2009, time.November, 10, 23, 0, 0, 0, loc)
	fmt.Println("The time is:", t.Format(time.RFC822))
}
Output:

The time is: 10 Nov 09 23:00 UTC-8

func LoadLocation

func LoadLocation(name string) (*Location, error)

LoadLocationは指定された名前を持つLocationを返します。

名前が""または"UTC"の場合、LoadLocationはUTCを返します。 名前が"Local"の場合、LoadLocationはLocalを返します。

それ以外の場合、名前はファイルに対応する場所の名前であり、 IANAタイムゾーンデータベースの中に存在します。例えば"America/New_York"です。

LoadLocationは以下の順序でIANAタイムゾーンデータベースを探します:

  • ZONEINFO環境変数によって指定されたディレクトリまたは解凍されたzipファイル
  • Unixシステムでは、システムの標準インストール場所
  • $GOROOT/lib/time/zoneinfo.zip
  • インポートされていた場合、time/tzdataパッケージ
Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	location, err := time.LoadLocation("America/Los_Angeles")
	if err != nil {
		panic(err)
	}

	timeInUTC := time.Date(2018, 8, 30, 12, 0, 0, 0, time.UTC)
	fmt.Println(timeInUTC.In(location))
}
Output:

2018-08-30 05:00:00 -0700 PDT

func LoadLocationFromTZData added in v1.10.0

func LoadLocationFromTZData(name string, data []byte) (*Location, error)

LoadLocationFromTZData returns a Location with the given name initialized from the IANA Time Zone database-formatted data. The data should be in the format of a standard IANA time zone file (for example, the content of /etc/localtime on Unix systems).

func (*Location) String

func (l *Location) String() string

Stringは、LoadLocationまたはFixedZoneのname引数に対応する、タイムゾーン情報の記述的な名前を返します。

type Month

type Month int

Monthは年の月を指定します(1月= 1、...)。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	_, month, day := time.Now().Date()
	if month == time.November && day == 10 {
		fmt.Println("Happy Go day!")
	}
}
Output:

const (
	January Month = 1 + iota
	February
	March
	April
	May
	June
	July
	August
	September
	October
	November
	December
)

func (Month) String

func (m Month) String() string

Stringは月の英語名(「January」、「February」、...)を返します。

type ParseError

type ParseError struct {
	Layout     string
	Value      string
	LayoutElem string
	ValueElem  string
	Message    string
}

ParseErrorは時間文字列を解析する際の問題を記述します。

func (*ParseError) Error

func (e *ParseError) Error() string

ErrorはParseErrorの文字列表現を返します。

type Ticker

type Ticker struct {
	C <-chan Time
	// contains filtered or unexported fields
}

Tickerは、時計の間隔で "ticks" を配信するチャネルを保持します。

func NewTicker

func NewTicker(d Duration) *Ticker

NewTickerは、各チック後にチャネルに現在の時刻を送信するチッカーを返します。チックの期間はduration引数で指定されます。チッカーは、遅い受信者のために時間間隔を調整するか、チックを削除します。 dの期間はゼロより大きくする必要があります。そうでない場合、NewTickerはパニックを起こします。チッカーを停止して関連するリソースを解放します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	done := make(chan bool)
	go func() {
		time.Sleep(10 * time.Second)
		done <- true
	}()
	for {
		select {
		case <-done:
			fmt.Println("Done!")
			return
		case t := <-ticker.C:
			fmt.Println("Current time: ", t)
		}
	}
}
Output:

func (*Ticker) Reset added in v1.15.0

func (t *Ticker) Reset(d Duration)

Resetはタイマーを停止し、指定された期間でタイマーをリセットします。 新しい期間が経過すると、次のティックが到着します。期間dは0より大きくなければなりません。もしそうでない場合、Resetはパニックを引き起こします。

func (*Ticker) Stop

func (t *Ticker) Stop()

Stopはティッカーを停止します。Stop後は、もうティックが送信されません。 Stopはチャネルを閉じないため、チャネルから読み取り中の並行ゴルーチンが誤った「ティック」を見ることを防ぎます。

type Time

type Time struct {
	// contains filtered or unexported fields
}

Timeは納秒単位の精度で時刻を表します。

Timeを使用するプログラムでは通常、値として保存し、渡すべきです。 つまり、時刻変数や構造体のフィールドは*time.Timeではなくtime.Timeの型であるべきです。

Timeの値は、GobDecode、UnmarshalBinary、UnmarshalJSON、UnmarshalTextメソッドを除いて、 複数のゴルーチンで同時に使用できます。

Timeの瞬間はBefore、After、Equalメソッドを使って比較することができます。 Subメソッドは2つの瞬間を引いてDurationを生成します。 AddメソッドはTimeとDurationを足してTimeを生成します。

Time型のゼロ値は、UTCでの1年1月1日00:00:00.000000000です。 この時刻は実際にはほとんど使われないため、IsZeroメソッドは明示的に初期化されていない時刻を検出するための簡単な方法です。

各TimeにはLocationが関連付けられており、Format、Hour、Yearメソッドなど、時刻の表示形式の計算時に参照されます。 メソッドLocal、UTC、Inは特定のLocationを持ったTimeを返します。 このようにして場所を変更すると、表示のみが変わり、指定された時刻の瞬間は変わらず、先の段落で説明される計算に影響を与えません。

GobEncode、MarshalBinary、MarshalJSON、MarshalTextメソッドによって保存されるTime値の表現には、Time.Locationのオフセットが格納されますが、 場所の名前は格納されません。そのため、夏時間に関する情報が失われます。

必要な「壁時計」の読み取りに加えて、Timeにはオプションのプロセスの単調な時計の読み取りが含まれることがあります。 比較や減算のための追加の精度を提供するためです。 詳細については、パッケージのドキュメントの「単調な時計」のセクションを参照してください。

Goの==演算子は、時刻の瞬間だけでなく、Locationと単調な時計の読み取りも比較します。 そのため、Timeの値は、まずすべての値に同じLocationが設定されていることを保証してから、 マップやデータベースのキーとして使用するべきではありません。これはUTCまたはLocalメソッドの使用によって実現でき、 単調な時計の読み取りはt = t.Round(0)と設定することで削除する必要があります。 一般的には、t.Equal(u)をt == uよりも優先し、t.Equalは最も正確な比較を使用し、 1つの引数のみが単調な時計の読み取りを持つ場合のケースを正しく処理します。

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Date関数は、与えられた場所と時間に対応するTimeZoneでの、 yyyy-mm-dd hh:mm:ss + nsecナノ秒のTimeを返します。

月、日、時、分、秒、nsecの値は通常の範囲外である場合でも、変換中に正規化されます。 例えば、10月32日は11月1日に変換されます。

夏時間の変遷では、一部の時間が飛ばされたり、繰り返されることがあります。 例えば、アメリカ合衆国では、2011年3月13日の2時15分は存在せず、 2011年11月6日の1時15分は2回存在します。そのような場合、 タイムゾーンの選択、つまり時間が明確でなくなります。 Date関数は、変遷に関与する2つのタイムゾーンのうちの1つで正確な時間を返しますが、 どちらかは保証されません。

locがnilの場合、Date関数はパニックを発生させます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
	fmt.Printf("Go launched at %s\n", t.Local())
}
Output:

Go launched at 2009-11-10 15:00:00 -0800 PST

func Now

func Now() Time

現在のローカル時間を返します。

func Parse

func Parse(layout, value string) (Time, error)

Parseは書式指定された文字列を解析し、それが表す時間の値を返します。 解析するには、レイアウトとして提供された形式文字列(レイアウト)を使用して、 第1引数として提供された解析可能な第2引数が必要です。

Time.Formatの例はレイアウト文字列の動作を詳しく説明しており、参考となります。

解析(Parse)時には、レイアウトがその存在を示していなくても、入力には秒の次に少数秒 フィールドが直ちに続く場合があります。その場合、最大連続桁の直後にカンマまたは 小数点が続くものを少数秒として解析します。少数秒はナノ秒まで切り捨てられます。

レイアウトから省略された要素はゼロであるか、ゼロが不可能な場合は1であるとみなされます。 したがって、"3:04pm"を解析すると、年0月1日15:04:00 UTCに対応する時間が返されます (年が0のため、この時間はゼロ時刻より前です)。 年は0000〜9999の範囲内である必要があります。曜日は構文チェックされますが、 それ以外は無視されます。

2桁の年06を指定するレイアウトの場合、値NN >= 69は19NNとして扱われ、 値NN < 69は20NNとして扱われます。

このコメントの残りの部分は、タイムゾーンの処理方法について説明しています。

タイムゾーン指示がない場合、ParseはUTCで時間を返します。

-0700のようなタイムゾーンオフセットを持つ時間を解析する場合、オフセットが現在の場所(ローカル)で使用されている タイムゾーンに対応している場合、Parseはその場所とタイムゾーンを使用して時間を返します。 そうでない場合は、与えられたゾーンオフセットで時間が固定された、架空の場所として時間を記録します。

MSTのようなタイムゾーン省略形を持つ時間を解析する場合、現在の場所で定義されたオフセットがある場合、それを使用します。 "UTC"というタイムゾーン省略形は、場所に関係なくUTCとして認識されます。 タイムゾーン省略形が不明な場合、Parseは与えられたゾーン省略形とゼロオフセットの架空の場所に 時間を記録します。この選択肢は、そのような時間をレイアウトの変更なしで解析および再フォーマットできますが、 表現に使用される正確な瞬間は実際のゾーンオフセットによって異なります。 そのような問題を回避するためには、数値のゾーンオフセットを使用する時間レイアウトを使用するか、ParseInLocationを使用してください。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {

	// Time.Formatの例を参照して、time.Time値を解析するためにレイアウト文字列を定義する方法の詳細を見てください。ParseとFormatは、入力と出力を記述するために同じモデルを使用します。

	// longFormは、参照時刻がどのように所望のレイアウトで表されるかを例示します。
	const longForm = "Jan 2, 2006 at 3:04pm (MST)"
	t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
	fmt.Println(t)

	// shortFormは望ましいレイアウトで参照時刻が表されるもう一つの方法です。これにはタイムゾーンが存在しません。
	// 注意:明示的なゾーンがない場合、時間はUTCで返されます。
	const shortForm = "2006-Jan-02"
	t, _ = time.Parse(shortForm, "2013-Feb-03")
	fmt.Println(t)

	// いくつかの有効なレイアウトは、スペースの埋め込みのための _ やゾーン情報のための Z などのフォーマット指定子によって無効な時間値となります。
	// たとえば、RFC3339のレイアウト 2006-01-02T15:04:05Z07:00 は、有効なオプションの両方を扱うために、Z とタイムゾーンオフセットの両方を含んでいます。
	// 2006-01-02T15:04:05Z
	// 2006-01-02T15:04:05+07:00
	t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
	fmt.Println(t)
	t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")
	fmt.Println(t)
	_, err := time.Parse(time.RFC3339, time.RFC3339)
	fmt.Println("error", err) // レイアウトが有効な時間の値ではないため、エラーが返されます。

}
Output:

2013-02-03 19:54:00 -0800 PST
2013-02-03 00:00:00 +0000 UTC
2006-01-02 15:04:05 +0000 UTC
2006-01-02 15:04:05 +0700 +0700
error parsing time "2006-01-02T15:04:05Z07:00": extra text: "07:00"

func ParseInLocation added in v1.1.0

func ParseInLocation(layout, value string, loc *Location) (Time, error)

ParseInLocationはParseと似ていますが、2つの重要な違いがあります。 まず、タイムゾーン情報がない場合、Parseは時間をUTCとして解釈しますが、 ParseInLocationは指定された場所の時間として解釈します。 さらに、ゾーンオフセットや略語が与えられた場合、Parseはそれをローカルの場所と照合しようとしますが、 ParseInLocationは指定された場所を使用します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	loc, _ := time.LoadLocation("Europe/Berlin")

	// これはEurope/Berlinの時刻帯でCESTという名前を探します。
	const longForm = "Jan 2, 2006 at 3:04pm (MST)"
	t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
	fmt.Println(t)

	// 注意:明示的なタイムゾーンがない場合、指定された場所の時間を返します。
	const shortForm = "2006-Jan-02"
	t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
	fmt.Println(t)

}
Output:

2012-07-09 05:02:00 +0200 CEST
2012-07-09 00:00:00 +0200 CEST

func Unix

func Unix(sec int64, nsec int64) Time

Unixは、与えられたUnix時刻に対応する現地時刻を返します。 secは1970年1月1日UTCからの秒数であり、nsecはナノ秒単位です。 nsecは[0、999999999]の範囲外を指定することもできます。 すべてのsec値に対応する時間値が存在するわけではありません。そのような値の一つは1 << 63-1(最大のint64値)です。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	unixTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
	fmt.Println(unixTime.Unix())
	t := time.Unix(unixTime.Unix(), 0).UTC()
	fmt.Println(t)

}
Output:

1257894000
2009-11-10 23:00:00 +0000 UTC

func UnixMicro added in v1.17.0

func UnixMicro(usec int64) Time

UnixMicroは、与えられたUnix時間に対応するローカル時間を返します。 usecは1970年1月1日UTCからのマイクロ秒です。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
	fmt.Println(umt.UnixMicro())
	t := time.UnixMicro(umt.UnixMicro()).UTC()
	fmt.Println(t)

}
Output:

1257894000000000
2009-11-10 23:00:00 +0000 UTC

func UnixMilli added in v1.17.0

func UnixMilli(msec int64) Time

UnixMilliは与えられたUnix時刻に対応するローカルの時刻を返します。 1970年1月1日UTCからのミリ秒で表されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	umt := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
	fmt.Println(umt.UnixMilli())
	t := time.UnixMilli(umt.UnixMilli()).UTC()
	fmt.Println(t)

}
Output:

1257894000000
2009-11-10 23:00:00 +0000 UTC

func (Time) Add

func (t Time) Add(d Duration) Time

Addは時間tにdを加えた時間を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	start := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
	afterTenSeconds := start.Add(time.Second * 10)
	afterTenMinutes := start.Add(time.Minute * 10)
	afterTenHours := start.Add(time.Hour * 10)
	afterTenDays := start.Add(time.Hour * 24 * 10)

	fmt.Printf("start = %v\n", start)
	fmt.Printf("start.Add(time.Second * 10) = %v\n", afterTenSeconds)
	fmt.Printf("start.Add(time.Minute * 10) = %v\n", afterTenMinutes)
	fmt.Printf("start.Add(time.Hour * 10) = %v\n", afterTenHours)
	fmt.Printf("start.Add(time.Hour * 24 * 10) = %v\n", afterTenDays)

}
Output:

start = 2009-01-01 12:00:00 +0000 UTC
start.Add(time.Second * 10) = 2009-01-01 12:00:10 +0000 UTC
start.Add(time.Minute * 10) = 2009-01-01 12:10:00 +0000 UTC
start.Add(time.Hour * 10) = 2009-01-01 22:00:00 +0000 UTC
start.Add(time.Hour * 24 * 10) = 2009-01-11 12:00:00 +0000 UTC

func (Time) AddDate

func (t Time) AddDate(years int, months int, days int) Time

AddDateはtに指定された年数、月数、日数を加算した時間を返します。 例えば、2011年1月1日にAddDate(-1, 2, 3)を適用すると、 2010年3月4日が返されます。

AddDateはDateと同じように結果を正規化します。 つまり、10月31日に1ヶ月を追加すると11月31日となり、 これは正規化されたフォームである12月1日になります。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	start := time.Date(2009, 1, 1, 0, 0, 0, 0, time.UTC)
	oneDayLater := start.AddDate(0, 0, 1)
	oneMonthLater := start.AddDate(0, 1, 0)
	oneYearLater := start.AddDate(1, 0, 0)

	fmt.Printf("oneDayLater: start.AddDate(0, 0, 1) = %v\n", oneDayLater)
	fmt.Printf("oneMonthLater: start.AddDate(0, 1, 0) = %v\n", oneMonthLater)
	fmt.Printf("oneYearLater: start.AddDate(1, 0, 0) = %v\n", oneYearLater)

}
Output:

oneDayLater: start.AddDate(0, 0, 1) = 2009-01-02 00:00:00 +0000 UTC
oneMonthLater: start.AddDate(0, 1, 0) = 2009-02-01 00:00:00 +0000 UTC
oneYearLater: start.AddDate(1, 0, 0) = 2010-01-01 00:00:00 +0000 UTC

func (Time) After

func (t Time) After(u Time) bool

tがuより後の時刻であるかどうかを報告します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
	year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)

	isYear3000AfterYear2000 := year3000.After(year2000) // 本当
	isYear2000AfterYear3000 := year2000.After(year3000) // 偽

	fmt.Printf("year3000.After(year2000) = %v\n", isYear3000AfterYear2000)
	fmt.Printf("year2000.After(year3000) = %v\n", isYear2000AfterYear3000)

}
Output:

year3000.After(year2000) = true
year2000.After(year3000) = false

func (Time) AppendFormat added in v1.5.0

func (t Time) AppendFormat(b []byte, layout string) []byte

AppendFormatはFormatと似ていますが、テキスト表現をbに追加し、拡張されたバッファを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	t := time.Date(2017, time.November, 4, 11, 0, 0, 0, time.UTC)
	text := []byte("Time: ")

	text = t.AppendFormat(text, time.Kitchen)
	fmt.Println(string(text))

}
Output:

Time: 11:00AM

func (Time) Before

func (t Time) Before(u Time) bool

Beforeは、時刻tがuよりも前であるかどうかを報告します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	year2000 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
	year3000 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)

	isYear2000BeforeYear3000 := year2000.Before(year3000) // 真
	isYear3000BeforeYear2000 := year3000.Before(year2000) // false

	fmt.Printf("year2000.Before(year3000) = %v\n", isYear2000BeforeYear3000)
	fmt.Printf("year3000.Before(year2000) = %v\n", isYear3000BeforeYear2000)

}
Output:

year2000.Before(year3000) = true
year3000.Before(year2000) = false

func (Time) Clock

func (t Time) Clock() (hour, min, sec int)

Clock 関数は、t で指定された日の時間、分、秒を返します。

func (Time) Compare added in v1.20.0

func (t Time) Compare(u Time) int

Compare関数は時刻tとuを比較します。tがuより前の場合は-1を返し、tがuより後の場合は+1を返します。同じである場合は0を返します。

func (Time) Date

func (t Time) Date() (year int, month Month, day int)

Dateはtが発生する年、月、日を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
	year, month, day := d.Date()

	fmt.Printf("year = %v\n", year)
	fmt.Printf("month = %v\n", month)
	fmt.Printf("day = %v\n", day)

}
Output:

year = 2000
month = February
day = 1

func (Time) Day

func (t Time) Day() int

Dayはtによって指定された月の日を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	d := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
	day := d.Day()

	fmt.Printf("day = %v\n", day)

}
Output:

day = 1

func (Time) Equal

func (t Time) Equal(u Time) bool

Equalは、tとuが同じ瞬間を表しているかどうかを報告します。 異なる場所にある場合でも、2つの時刻が等しい場合があります。 たとえば、6:00 +0200と4:00 UTCはEqualです。 Timeのドキュメントを参照して、==を使用する際の注意点を確認してください。 ほとんどのコードはEqualを使用する必要があります。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	secondsEastOfUTC := int((8 * time.Hour).Seconds())
	beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)

	// equal演算子とは異なり、Equalはd1とd2が同じ瞬間であることを時差が異なるものとして認識しています。
	d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
	d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing)

	datesEqualUsingEqualOperator := d1 == d2
	datesEqualUsingFunction := d1.Equal(d2)

	fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator)
	fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction)

}
Output:

datesEqualUsingEqualOperator = false
datesEqualUsingFunction = true

func (Time) Format

func (t Time) Format(layout string) string

Formatは、引数で定義されたレイアウトに従って、時刻値のテキスト表現を返します。レイアウトフォーマットの表現方法については、「Layout」という定数のドキュメントを参照してください。

Time.Formatの実行可能な例は、レイアウト文字列の詳細な動作を示しており、参考になります。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	// 標準のUnix形式の文字列から時刻値を解析する。
	t, err := time.Parse(time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")
	if err != nil { // 必ずエラーを確認する。たとえそれが起こらないはずでも。
		panic(err)
	}

	tz, err := time.LoadLocation("Asia/Shanghai")
	if err != nil { // 常にエラーチェックを行います。たとえ起こるべきでない場合でも。
		panic(err)
	}

	// time.TimeのStringerメソッドは、フォーマットなしでも便利です。
	fmt.Println("default format:", t)

	// パッケージ内の予め定義された定数は、共通のレイアウトを実装します。
	fmt.Println("Unix format:", t.Format(time.UnixDate))

	// 時間値に付けられたタイムゾーンは出力に影響を与えます。
	fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))

	fmt.Println("in Shanghai with seconds:", t.In(tz).Format("2006-01-02T15:04:05 -070000"))

	fmt.Println("in Shanghai with colon seconds:", t.In(tz).Format("2006-01-02T15:04:05 -07:00:00"))

	// この関数の残りの部分は、フォーマットに使用されるレイアウト文字列の特性を示しています。

	// Parse関数とFormatメソッドで使用されるレイアウト文字列は、
	// 参照時刻の表現方法を例示します。
	// 強調することは、参照時刻のフォーマット方法を示す必要があるということであり、
	// ユーザーが選択した時刻ではありません。そのため、各レイアウト文字列は
	// 時刻スタンプの表現です。
	// Jan 2 15:04:05 2006 MST
	// この値を覚えるための簡単な方法は、この順序で表示されたときに、
	// 上記の要素と一致する値を保持していることです。
	// 1 2 3 4 5 6 -7
	// 以下では、いくつかの例が示されています。

	// FormatやParseのほとんどの使用例は、このパッケージで定義されているような定数のレイアウト文字列を使用しますが、
	// これらの例が示すように、インタフェースは柔軟です。

	// 例の出力を見やすくするためのヘルパー関数を定義する。
	do := func(name, layout, want string) {
		got := t.Format(layout)
		if want != got {
			fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
			return
		}
		fmt.Printf("%-16s %q gives %q\n", name, layout, got)
	}

	// 出力にヘッダーを表示します。
	fmt.Printf("\nFormats:\n\n")

	// シンプルなスターターの例。
	do("Basic full date", "Mon Jan 2 15:04:05 MST 2006", "Wed Feb 25 11:06:39 PST 2015")
	do("Basic short date", "2006/01/02", "2015/02/25")

	// 参照時刻の時は15、または午後3時です。レイアウトはどちらの形式でも表現できますが、私たちの値は朝の時間なので、AMとして表示する必要があります。両方を1つの書式文字列で表示します。小文字でも。
	do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")

	t, err = time.Parse(time.UnixDate, "Wed Feb 25 11:06:39.1234 PST 2015")
	if err != nil {
		panic(err)
	}

	// レイアウト文字列に少数秒の表現が含まれていない場合、出力には表示されません。
	do("No fraction", time.UnixDate, "Wed Feb 25 11:06:39 PST 2015")

	// 配列文字列の中で、秒数の値の小数点以下に0または9が連続していると、小数点以下の秒数が表示されます。
	// レイアウトの桁が0の場合、指定された桁数の小数秒になります。ただし、出力には末尾に0が付きます。
	do("0s for fraction", "15:04:05.00000", "11:06:39.12340")

	// レイアウト内の小数部が9sの場合、末尾のゼロは削除されます。
	do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")

}
Output:

default format: 2015-02-25 11:06:39 -0800 PST
Unix format: Wed Feb 25 11:06:39 PST 2015
Same, in UTC: Wed Feb 25 19:06:39 UTC 2015
in Shanghai with seconds: 2015-02-26T03:06:39 +080000
in Shanghai with colon seconds: 2015-02-26T03:06:39 +08:00:00

Formats:

Basic full date  "Mon Jan 2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
Basic short date "2006/01/02" gives "2015/02/25"
AM/PM            "3PM==3pm==15h" gives "11AM==11am==11h"
No fraction      "Mon Jan _2 15:04:05 MST 2006" gives "Wed Feb 25 11:06:39 PST 2015"
0s for fraction  "15:04:05.00000" gives "11:06:39.12340"
9s for fraction  "15:04:05.99999999" gives "11:06:39.1234"
Example (Pad)
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	// 標準のUnix形式の文字列から時間値を解析します。
	t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
	if err != nil { // 必要ないと思われるかもしれないが、常にエラーをチェックしてください。
		panic(err)
	}

	// ヘルパー関数を定義して、例の出力を見やすくします。
	do := func(name, layout, want string) {
		got := t.Format(layout)
		if want != got {
			fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
			return
		}
		fmt.Printf("%-16s %q gives %q\n", name, layout, got)
	}

	// 予定された定数 Unix は日を埋めるためにアンダースコアを使用します。
	do("Unix", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")

	// 固定幅で値をプリントするために、日付などの1文字または2文字になる可能性がある場合、レイアウト文字列の代わりにスペースの代わりに_を使用します。
	// ここでは、レイアウト文字列では2で値は7の日を印刷しています。
	do("No pad", "<2>", "<7>")

	// アンダースコアはスペースのパッドを表します。日付が1桁の場合。
	do("Spaces", "<_2>", "< 7>")

	// "0"は一桁の値のゼロ埋めを示します。
	do("Zeros", "<02>", "<07>")

	// 値がすでに適切な幅である場合、パディングは使用されません。
	// たとえば、値の2番目(リファレンス時刻の05)は39ですが、
	// したがって、パディングは必要ありませんが、分の部分(04, 06)には必要です。
	do("Suppressed pad", "04:05", "06:39")

}
Output:

Unix             "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
No pad           "<2>" gives "<7>"
Spaces           "<_2>" gives "< 7>"
Zeros            "<02>" gives "<07>"
Suppressed pad   "04:05" gives "06:39"

func (Time) GoString added in v1.17.0

func (t Time) GoString() string

GoStringはfmt.GoStringerを実装し、Goソースコードで表示されるようにtをフォーマットします。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
	fmt.Println(t.GoString())
	t = t.Add(1 * time.Minute)
	fmt.Println(t.GoString())
	t = t.AddDate(0, 1, 0)
	fmt.Println(t.GoString())
	t, _ = time.Parse("Jan 2, 2006 at 3:04pm (MST)", "Feb 3, 2013 at 7:54pm (UTC)")
	fmt.Println(t.GoString())

}
Output:

time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
time.Date(2009, time.November, 10, 23, 1, 0, 0, time.UTC)
time.Date(2009, time.December, 10, 23, 1, 0, 0, time.UTC)
time.Date(2013, time.February, 3, 19, 54, 0, 0, time.UTC)

func (*Time) GobDecode

func (t *Time) GobDecode(data []byte) error

GobDecodeはgob.GobDecoderインターフェースを実装します。

func (Time) GobEncode

func (t Time) GobEncode() ([]byte, error)

GobEncodeはgob.GobEncoderインターフェースを実装します。

func (Time) Hour

func (t Time) Hour() int

Hourはtで指定された日の中の時間を返します。範囲は[0, 23]です。

func (Time) ISOWeek

func (t Time) ISOWeek() (year, week int)

ISOWeekは、tが発生するISO 8601の年と週番号を返します。 週は1から53までの範囲です。年nの1月1日から1月3日は年n-1の週52または53に属する場合があり、12月29日から12月31日は年n+1の週1に属する場合があります。

func (Time) In

func (t Time) In(loc *Location) Time

In は、同じ時刻インスタンスを表す t のコピーを返しますが、表示目的でコピーの場所情報を loc に設定します。

loc が nil の場合、In はパニックを発生させます。

func (Time) IsDST added in v1.17.0

func (t Time) IsDST() bool

IsDSTは、設定された場所の時刻が夏時間(Daylight Savings Time)かどうかを報告します。

func (Time) IsZero

func (t Time) IsZero() bool

IsZero は t がゼロのタイムインスタント(西暦1年1月1日00:00:00 UTC)を表すかどうかを報告します。

func (Time) Local

func (t Time) Local() Time

Local は t の位置をローカルの時間に設定して返します。

func (Time) Location

func (t Time) Location() *Location

Locationは、tに関連付けられたタイムゾーン情報を返します。

func (Time) MarshalBinary added in v1.2.0

func (t Time) MarshalBinary() ([]byte, error)

MarshalBinaryはencoding.BinaryMarshalerインターフェースを実装します。

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSONはjson.Marshalerインターフェースを実装します。 時刻はRFC 3339形式で引用符で囲まれた文字列です。秒未満の精度もあります。 タイムスタンプが有効なRFC 3339として表現できない場合 (例:年が範囲外の場合)、エラーが報告されます。

func (Time) MarshalText added in v1.2.0

func (t Time) MarshalText() ([]byte, error)

MarshalTextはencoding.TextMarshalerインターフェースを実装します。 時間はRFC 3339形式でサブ秒の精度でフォーマットされます。 タイムスタンプが有効なRFC 3339として表現できない場合(例:年が範囲外の場合)、エラーが報告されます。

func (Time) Minute

func (t Time) Minute() int

Minuteは時間tで指定された時間内の分のオフセットを、[0、59]の範囲で返します。

func (Time) Month

func (t Time) Month() Month

Month は t で指定された年の月を返します。

func (Time) Nanosecond

func (t Time) Nanosecond() int

Nanosecondはtで指定された秒の中でのナノ秒オフセットを[0, 999999999]の範囲で返します。

func (Time) Round added in v1.1.0

func (t Time) Round(d Duration) Time

Roundはtを最も近いdの倍数に丸めた結果を返します(ゼロ時からの経過時間を使います)。 半分の値の丸め方は切り上げです。 d <= 0の場合、Roundはtをモノトニックな時計読み取りを除いて変更せずに返します。

Roundは時間の表示形式ではなく、ゼロ時からの絶対経過時間として動作します。 したがって、Round(Hour)は時間のLocationによって非ゼロの分を持つことがあります。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
	round := []time.Duration{
		time.Nanosecond,
		time.Microsecond,
		time.Millisecond,
		time.Second,
		2 * time.Second,
		time.Minute,
		10 * time.Minute,
		time.Hour,
	}

	for _, d := range round {
		fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
	}
}
Output:

t.Round(   1ns) = 12:15:30.918273645
t.Round(   1µs) = 12:15:30.918274
t.Round(   1ms) = 12:15:30.918
t.Round(    1s) = 12:15:31
t.Round(    2s) = 12:15:30
t.Round(  1m0s) = 12:16:00
t.Round( 10m0s) = 12:20:00
t.Round(1h0m0s) = 12:00:00

func (Time) Second

func (t Time) Second() int

Secondは、tで指定された分の中の2番目のオフセットを、[0, 59]の範囲で返します。

func (Time) String

func (t Time) String() string

Stringはフォーマット文字列を使用して書式付けされた時間を返します

"2006-01-02 15:04:05.999999999 -0700 MST"

もし時間が単調なクロック読み取りを持っている場合、返される文字列は "m=±<value>"という最後のフィールドを含みます。ここで、valueは 単調なクロック読み取りを秒で表した10進数です。

返される文字列はデバッグ用途であり、安定したシリアライズされた表現には t.MarshalText、t.MarshalBinary、または明示的なフォーマット文字列を使用した t.Formatを使用してください。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	timeWithNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 15, time.UTC)
	withNanoseconds := timeWithNanoseconds.String()

	timeWithoutNanoseconds := time.Date(2000, 2, 1, 12, 13, 14, 0, time.UTC)
	withoutNanoseconds := timeWithoutNanoseconds.String()

	fmt.Printf("withNanoseconds = %v\n", string(withNanoseconds))
	fmt.Printf("withoutNanoseconds = %v\n", string(withoutNanoseconds))

}
Output:

withNanoseconds = 2000-02-01 12:13:14.000000015 +0000 UTC
withoutNanoseconds = 2000-02-01 12:13:14 +0000 UTC

func (Time) Sub

func (t Time) Sub(u Time) Duration

Subは期間t-uを返します。結果がDurationに格納できる最大値(または最小値)を超える場合、最大(または最小)の期間が返されます。 期間dのt-dを計算するためには、t.Add(-d)を使用してください。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	start := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
	end := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC)

	difference := end.Sub(start)
	fmt.Printf("difference = %v\n", difference)

}
Output:

difference = 12h0m0s

func (Time) Truncate added in v1.1.0

func (t Time) Truncate(d Duration) Time

Truncate関数は、tをd(ゼロ時点からの倍数)に切り捨てた結果を返します。 もしd <= 0の場合、Truncateはmonotonicなクロックの読み取りを除いたtを返しますが、それ以外は変更されません。

Truncateは、時間をゼロ時点からの絶対経過時間として操作します。 時間の表現形式ではなく、時刻を操作します。したがって、Truncate(Hour)は、 時刻のLocationに依存して、非ゼロの分を持つ時刻を返す場合があります。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
	trunc := []time.Duration{
		time.Nanosecond,
		time.Microsecond,
		time.Millisecond,
		time.Second,
		2 * time.Second,
		time.Minute,
		10 * time.Minute,
	}

	for _, d := range trunc {
		fmt.Printf("t.Truncate(%5s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
	}
	// ローカルタイムゾーンの最後の深夜に丸めるには、新しい日付を作成します。
	midnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
	_ = midnight

}
Output:

t.Truncate(  1ns) = 12:15:30.918273645
t.Truncate(  1µs) = 12:15:30.918273
t.Truncate(  1ms) = 12:15:30.918
t.Truncate(   1s) = 12:15:30
t.Truncate(   2s) = 12:15:30
t.Truncate( 1m0s) = 12:15:00
t.Truncate(10m0s) = 12:10:00

func (Time) UTC

func (t Time) UTC() Time

UTCは場所をUTCに設定したtを返します。

func (Time) Unix

func (t Time) Unix() int64

UnixはtをUnix時刻として返します。これは1970年1月1日UTCからの経過秒数です。結果はtに関連付けられた場所に依存しません。 Unix系のオペレーティングシステムはしばしば時間を32ビットの秒数として記録しますが、ここで返される値は64ビットのため、過去や未来の数十億年に対しても有効です。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/time"
)

func main() {
	// Unixの10億秒、3つの方法。
	fmt.Println(time.Unix(1e9, 0).UTC())     // 1億秒
	fmt.Println(time.Unix(0, 1e18).UTC())    // 1e18ナノ秒
	fmt.Println(time.Unix(2e9, -1e18).UTC()) // 2e9 秒 - 1e18 ナノ秒

	t := time.Date(2001, time.September, 9, 1, 46, 40, 0, time.UTC)
	fmt.Println(t.Unix())     // 1970年からの経過時間(秒)
	fmt.Println(t.UnixNano()) // 1970 年以来のナノ秒

}
Output:

2001-09-09 01:46:40 +0000 UTC
2001-09-09 01:46:40 +0000 UTC
2001-09-09 01:46:40 +0000 UTC
1000000000
1000000000000000000

func (Time) UnixMicro added in v1.17.0

func (t Time) UnixMicro() int64

UnixMicroは、tをUnix時間として返します。これは、1970年1月1日UTCから経過したマイクロ秒の数です。int64で表現できない場合(年-290307以前または年294246以降の日付)、結果は未定義です。結果は、tに関連付けられた場所に依存しません。

func (Time) UnixMilli added in v1.17.0

func (t Time) UnixMilli() int64

UnixMilliはtをUnix時刻として返します。つまり、1970年1月1日UTCから経過したミリ秒の数です。int64で表現できない(1970年より292万年以上前または後の日付)場合、結果は未定義です。結果はtに関連付けられた場所に依存しません。

func (Time) UnixNano

func (t Time) UnixNano() int64

UnixNanoはtをUnix時刻として返します。これは、1970年1月1日UTCから経過したナノ秒数です。Unix時刻がint64で表現できない場合(1678年以前または2262年以降の日付)、結果は未定義です。なお、これはゼロのTimeに対してUnixNanoを呼び出した結果も未定義であることを意味します。結果はtに関連付けられた場所に依存しません。

func (*Time) UnmarshalBinary added in v1.2.0

func (t *Time) UnmarshalBinary(data []byte) error

UnmarshalBinaryはencoding.BinaryUnmarshalerインターフェースを実装します。

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSONはjson.Unmarshalerインターフェースを実装します。 時刻はRFC 3339形式でクォートされた文字列である必要があります。

func (*Time) UnmarshalText added in v1.2.0

func (t *Time) UnmarshalText(data []byte) error

UnmarshalTextはencoding.TextUnmarshalerインターフェースを実装します。 時刻はRFC 3339形式である必要があります。

func (Time) Weekday

func (t Time) Weekday() Weekday

Weekdayはtに指定された曜日を返します。

func (Time) Year

func (t Time) Year() int

Yearはtが発生する年を返します。

func (Time) YearDay added in v1.1.0

func (t Time) YearDay() int

YearDay は与えられた t によって指定される年の日を返します。 非閏年の場合、範囲は [1, 365] であり、閏年の場合は [1, 366] です。

func (Time) Zone

func (t Time) Zone() (name string, offset int)

Zone関数は、時刻tに有効なタイムゾーンを計算し、タイムゾーンの省略名(「CET」など)とUTCから東へのオフセットを秒単位で返します。

func (Time) ZoneBounds added in v1.19.0

func (t Time) ZoneBounds() (start, end Time)

ZoneBoundsは、時刻tに有効なタイムゾーンの範囲を返します。 ゾーンはstartで始まり、次のゾーンはendで始まります。 ゾーンが時間の開始時点で始まる場合、startはゼロの時間として返されます。 ゾーンが永遠に続く場合、endはゼロの時間として返されます。 返された時間の場所はtと同じになります。

type Timer

type Timer struct {
	C <-chan Time
	// contains filtered or unexported fields
}

Timer型は単一のイベントを表します。 Timerが時間切れになると、現在の時間がCに送信されます。 ただし、TimerがAfterFuncによって作成された場合は除きます。 TimerはNewTimerまたはAfterFuncで作成する必要があります。

func AfterFunc

func AfterFunc(d Duration, f func()) *Timer

AfterFuncは、指定した時間が経過した後、fを自身のゴルーチンで呼び出します。 Stopメソッドを使用して呼び出しをキャンセルするために使用できるTimerを返します。

func NewTimer

func NewTimer(d Duration) *Timer

NewTimerは、少なくともdの期間経過後に、 そのチャネルに現在の時刻を送信する新しいTimerを作成します。

func (*Timer) Reset added in v1.1.0

func (t *Timer) Reset(d Duration) bool

Resetはタイマーを期間d後に期限切れにする。 タイマーがアクティブであった場合はtrue、期限切れまたは停止された場合はfalseを返す。

NewTimerで作成されたタイマーの場合、Resetは停止または期限切れのタイマーにのみ呼び出すべきです。チャネルが空になっている必要があります。

プログラムがすでにt.Cから値を受け取っている場合、タイマーは期限切れであり、チャネルは空になっているため、t.Resetを直接使用できます。 しかし、まだt.Cから値を受け取っていない場合、タイマーは停止しなければならず、Stopがタイマーが停止される前に期限切れしたことを報告した場合は、 チャネルを明示的に空にする必要があります:

if !t.Stop() {
	<-t.C
}
t.Reset(d)

これは、他の受信操作と同時に行うべきではありません。

Resetの返り値を正しく使用することはできないことに注意してください。チャネルの空にする操作と新しいタイマーの期限切れとの競合状態があります。 上記に説明したように、Resetは必ず停止または期限切れのチャネルに対して呼び出すべきです。返り値は、既存のプログラムとの互換性を保つために存在します。

AfterFunc(d, f)で作成されたタイマーの場合、Resetはfが実行されるタイミングを再スケジュールするかどうかによってtrueまたはfalseを返します。 Resetがfalseを返す場合、Resetは前のfが完了するのを待たずにリターンせず、また後続のgoroutineが前のgoroutineと同時に実行されないことを保証しません。 前のfが完了したかどうかを知る必要がある場合、明示的にfと調整する必要があります。

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop prevents the Timer from firing. It returns true if the call stops the timer, false if the timer has already expired or been stopped. Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.

To ensure the channel is empty after a call to Stop, check the return value and drain the channel. For example, assuming the program has not received from t.C already:

if !t.Stop() {
	<-t.C
}

This cannot be done concurrent to other receives from the Timer's channel or other calls to the Timer's Stop method.

For a timer created with AfterFunc(d, f), if t.Stop returns false, then the timer has already expired and the function f has been started in its own goroutine; Stop does not wait for f to complete before returning. If the caller needs to know whether f is completed, it must coordinate with f explicitly.

type Weekday

type Weekday int

Weekdayは、週の日を指定します(日曜日 = 0、...)。

const (
	Sunday Weekday = iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
)

func (Weekday) String

func (d Weekday) String() string

Stringは日の英語名("Sunday", "Monday", ...)を返します。

Directories

Path Synopsis
tzdata パッケージは、タイムゾーンデータベースの埋め込みコピーを提供します。
tzdata パッケージは、タイムゾーンデータベースの埋め込みコピーを提供します。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL