0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

time.Date関数は繰り上がりを適切に処理してくれる

Last updated at Posted at 2018-03-08

goのtime.Date関数がerrorを返さない関数だったので、通常の範囲外の値を渡したらどうなるのかと思ってやってみたら、ちゃんと繰り上がり処理されていた。

リファレンスにもちゃんと書いてあった。

The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

以下のように実行することができる。


package main

import (
	"fmt"
	"time"
)

func main() {

	// 月/日の繰り上がり
	fmt.Println(time.Date(2018, 14, 1, 0, 0, 0, 0, time.UTC).Format("2006-01-02 15:04:05")) // 2019-02-01 00:00:00
	fmt.Println(time.Date(2018, 1, 40, 0, 0, 0, 0, time.UTC).Format("2006-01-02 15:04:05")) // 2018-02-09 00:00:00

	// 時/分/秒/ナノ秒の繰り上がり
	fmt.Println(time.Date(2018, 1, 1, 26, 0, 0, 0, time.UTC).Format("2006-01-02 15:04:05"))             // 2018-01-02 02:00:00
	fmt.Println(time.Date(2018, 1, 1, 0, 80, 0, 0, time.UTC).Format("2006-01-02 15:04:05"))             // 2018-01-01 01:20:00
	fmt.Println(time.Date(2018, 1, 1, 0, 0, 80, 0, time.UTC).Format("2006-01-02 15:04:05"))             // 2018-01-01 00:01:20
	fmt.Println(time.Date(2018, 1, 1, 0, 0, 0, 2000*1000*1000, time.UTC).Format("2006-01-02 15:04:05")) // 2018-01-01 00:00:02

	// 全部
	fmt.Println(time.Date(2018, 13, 32, 24, 60, 60, 1000*1000*1000, time.UTC).Format("2006-01-02 15:04:05")) // 2019-02-02 01:01:01
}

自分の用途では27時とかを繰り上がりしたかったので、便利だった。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?