Skip to content

Instantly share code, notes, and snippets.

@mkfsn
Last active April 2, 2019 09:11
Show Gist options
  • Save mkfsn/2c96cc81376a42b119cd9f05da817857 to your computer and use it in GitHub Desktop.
Save mkfsn/2c96cc81376a42b119cd9f05da817857 to your computer and use it in GitHub Desktop.
西暦→和暦変換
package main
import (
"errors"
"fmt"
"time"
)
var (
asiaTokyo *time.Location
eras []JapaneseEra
ErrNotImplemented = errors.New("not implemented yet")
)
type JapaneseEra struct {
Name string
Date time.Time
}
func init() {
asiaTokyo, _ = time.LoadLocation("Asia/Tokyo")
eras = []JapaneseEra{
{Name: "令和", Date: time.Date(2019, 5, 1, 0, 0, 0, 0, asiaTokyo)},
{Name: "平成", Date: time.Date(1989, 1, 8, 0, 0, 0, 0, asiaTokyo)},
{Name: "昭和", Date: time.Date(1926, 12, 25, 0, 0, 0, 0, asiaTokyo)},
{Name: "大正", Date: time.Date(1912, 7, 30, 0, 0, 0, 0, asiaTokyo)},
{Name: "明治", Date: time.Date(1868, 9, 8, 0, 0, 0, 0, asiaTokyo)},
}
}
func convert(d time.Time) (string, int, error) {
for _, era := range eras {
if d.After(era.Date) || d == era.Date {
return era.Name, d.Year() - era.Date.Year(), nil
}
}
return "", 0, ErrNotImplemented
}
func main() {
now := time.Now()
name, year, _ := convert(time.Now())
fmt.Printf("%v => %s%d年", now.Format("2006/01/02"), name, year)
}
@PichuChen
Copy link

@PichuChen
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment