如何将 Golang 中的年份转换为佛教年份

huangapple go评论91阅读模式
英文:

How to convert year in Golang to Buddhist year

问题

基本上,如果我运行这段代码,我可以得到日期

t := time.Now()
fmt.Println(t.Format("02/01/2006"))

我的问题是如何将Go语言的年份转换为佛教年份的格式?

注意 将公元年份转换为佛历年份的公式是

佛历年份 = 公元年份 + 543
英文:

Basically, If I run this code I can get date

t := time.Now()
fmt.Println(t.Format("02/01/2006"))

My question is how to convert Go year to Buddhist year in this format?

Note a formula for converting year in A.D. to B.E format is

B.E. = A.D. + 543

答案1

得分: 3

我认为下面的代码存在一个闰年的 bug。

t := time.Now()
buddhaTime = t.AddDate(543, 0, 0)

如果年份是闰年,比如2020年,那么佛历年份将会是2020+543,即2563年。但是Golang的时间处理会将2563年理解为公元纪年,而实际上,公元纪年的2563年并不是闰年。因此,在每个闰年的2月29日和3月1日之间会产生冲突。例如,如果你尝试转换2020年2月29日,你将会得到佛历纪元的结果为2563年3月1日。

因此,我认为解决方案是先检测是否为闰年,然后再处理格式。

func IsLeapYear(date time.Time) bool {
   endOfYear := time.Date(date.Year(), time.December, 31, 0, 0, 0, 0, time.Local)
   day := endOfYear.YearDay()
   return day == 366
}
func ConvertDateToBuddhistEra(date time.Time) string {
   if IsLeapYear(date) {
      y := date.Year()+543
      return fmt.Sprintf("%s/%s/%d", date.Format("02"), date.Format("01"), y)
   }
   return date.AddDate(543, 0, 0).Format("02/01/2006")
}

对该库进行更新以修复问题会很好。

英文:

I think this way below has a bug in leap year.

t := time.Now()
buddhaTime = t.AddDate(543, 0, 0)

If the year is a leap year such as 2020, then the Buddhist year will be 2020+543 which is 2563. But Golang time will understand that 2563 is in the Christ year But actually, 2563 in Christ year is not a leap year. So, there will be a conflict on 29 Feb and 1 Mar in every leap year. For example, If you try to convert 29/02/2020, you will get 01/03/2563 as a result in buddhist era.

So I think the solution is to detect the leap year first and then handle the format.

func IsLeapYear(date time.Time) bool {
   endOfYear := time.Date(date.Year(), time.December, 31, 0, 0, 0, 0, time.Local)
   day := endOfYear.YearDay()
   return day == 366
}
func ConvertDateToBuddhistEra(date time.Time) string {
   if IsLeapYear(date) {
      y := date.Year()+543
      return fmt.Sprintf("%s/%s/%d", date.Format("02"), date.Format("01"), y)
   }
   return date.AddDate(543, 0, 0).Format("02/01/2006")
}

an update format to the lib would be nice.

答案2

得分: 2

好的,以下是翻译好的内容:

我非常怀疑是否存在一种格式字符串可以生成佛教时间,所以你可以简单直接地将543年添加到你的日期上...你应该为beDifference使用一个常量。

t := time.Now()
buddhaTime := t.AddDate(543, 0, 0)
英文:

Well I highly doubt that a format string exists which will product Buddhist time so just do the simple straight forward thing and add 543 years to your date... You should probably use a constant for the beDifference.

t := time.Now()
buddhaTime = t.AddDate(543, 0, 0)

huangapple
  • 本文由 发表于 2016年4月21日 07:11:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/36756834.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定