Open Evereen2023 opened 2 hours ago
// 解析输入的时间
t, err := time.Parse("2006-01-02", dateStr)
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"error": "invalid time format, should be YYYY-MM-DD"})
return
}
ai解决方法如下: // 自定义计算民用昏朦的函数 func CalculateCivilTwilight(t time.Time, long float64, lat float64) (time.Time, time.Time, error) { // 计算日出和日落时间(可以使用已有的sun.RiseTime和sun.DownTime) sunrise, err := sun.RiseTime(t, long, lat, 0, true) if err != nil { return time.Time{}, time.Time{}, err } sunset, err := sun.DownTime(t, long, lat, 0, true) if err != nil { return time.Time{}, time.Time{}, err }
// 计算民用昏暗的开始和结束时间,假设太阳高度角为-6度
morningTwilight := sunrise.Add(-time.Minute * 30) // 假设30分钟为民用昏暗开始时间
eveningTwilight := sunset.Add(time.Minute * 30) // 假设30分钟为民用昏暗结束时间
return morningTwilight, eveningTwilight, nil
}
时区转换存在bug,目前您可以在解析时间时手动设置时区暂时规避这个问题,这个bug会尽快修复:
// 解析输入的时间
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
//do something
}
now, t := time.ParseInLocation("2006-01-02", dateStr, loc)
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{"error": "invalid time format, should be YYYY-MM-DD"})
return
}
{ "eveningTwilight": "2024-10-22T09:13:00+08:00", "morningTwilight": "2024-10-21T21:32:35+08:00", "sunrise": "2024-10-22T06:01:57+08:00", "sunset": "2024-10-22T16:43:40+08:00" } 最后返回的是这个,而气象局当天给出的是 05:33 至 06:02 | 29 分钟
time.Parse() 将字符串转换为time.Time
对象,对象中默认时区是UTC时间,也就是北京时间-8小时。
sun.MorningTwilight()
计算出朦影时间后,忽视了time.Time
对象时区强行转为当地时间,导致了bug。
morningTwilight": "2024-10-21T21:32:35+08:00
再加8小时就是 "2024-10-22T05:32:35+08:00
,与气象局的05:33一致。
latitude=43.8860&longitude=125.3245&date=2024-10-22 我的api传参为此,本人在长春所以算的是长春的
{ "eveningTwilight": "2024-10-22T09:13:00+08:00", "morningTwilight": "2024-10-21T21:32:35+08:00", "sunrise": "2024-10-22T06:01:57+08:00", "sunset": "2024-10-22T16:43:40+08:00" }
最后返回的是这个,而气象局当天给出的是 05:33 至 06:02 | 29 分钟api中涉及astro的函数
MorningTwilight, err := sun.MorningTwilight(t, long, lat, -6) if err != nil { context.JSON(http.StatusInternalServerError, gin.H{"error": "failed to calculate civil twilight start time"}) return } EveningTwilight, err := sun.EveningTwilight(t, long, lat, -6) if err != nil { context.JSON(http.StatusInternalServerError, gin.H{"error": "failed to calculate civil twilight end time"}) return }
// 返回结果 context.JSON(http.StatusOK, gin.H{ "sunrise": sunRise.Format(time.RFC3339), "sunset": sunSet.Format(time.RFC3339), "morningTwilight": MorningTwilight.Format(time.RFC3339), "eveningTwilight": EveningTwilight.Format(time.RFC3339), })