Last active
April 2, 2019 09:11
-
-
Save mkfsn/2c96cc81376a42b119cd9f05da817857 to your computer and use it in GitHub Desktop.
西暦→和暦変換
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/mkfsn/2c96cc81376a42b119cd9f05da817857#file-jpn_year-go-L34
Change to
!era.Date.Before(d)
?