我有一个从API中获取的对象,它有一个特定日期的餐厅时间表:
restaurantTimetable := []string {
"2023-05-27T11:00:00",
"2023-05-27T11:30:00",
"2023-05-27T12:00:00",
"2023-05-27T12:30:00",
"2023-05-27T13:00:00",
"2023-05-27T13:30:00",
"2023-05-27T14:00:00",
"2023-05-27T18:00:00",
"2023-05-27T18:30:00",
"2023-05-27T19:00:00",
"2023-05-27T19:30:00",
"2023-05-27T20:00:00",
"2023-05-27T20:30:00",
"2023-05-27T21:00:00",
}
我想把它解析成类似这样的东西,这样我们就有了当天的开放和关闭时间:
[
{
"open": {
"time": "1100",
"hours": 11,
"minutes": 0,
"nextDate": 0
},
"close": {
"time": "1400",
"hours": 14,
"minutes": 0,
"nextDate": 0
}
},
{
"open": {
"time": "1800",
"hours": 18,
"minutes": 0,
"nextDate": 0
},
"close": {
"time": "2100",
"hours": 21,
"minutes": 0,
"nextDate": 0
}
}
]
这就是我到目前为止所做的,但我没有得到正确的结果,我不知道到底出了什么问题:
func ParseTimetable(timetable []string) ([]map[string]map[string]interface{}, error) {
const layout = "2006-01-02T15:04:05"
slots := make([]map[string]map[string]interface{}, 0)
for i := 0; i+1 < len(timetable); i += 2 {
startSlot := timetable[i]
endSlot := timetable[i+1]
// parse start and end times as time.Time objects
startTime, err := time.Parse(layout, startSlot)
if err != nil {
return nil, err
}
endTime, err := time.Parse(layout, endSlot)
if err != nil {
return nil, err
}
startHour, startMinute, _ := startTime.Clock()
endHour, endMinute, _ := endTime.Clock()
slot := map[string]map[string]interface{}{
"open": {
"time": fmt.Sprintf("%02d%02d", startHour, startMinute),
"hours": startHour,
"minutes": startMinute,
"nextDate": 0,
},
"close": {
"time": fmt.Sprintf("%02d%02d", endHour, endMinute),
"hours": endHour,
"minutes": endMinute,
"nextDate": 0,
},
}
slots = append(slots, slot)
}
return slots, nil
}
我不知道我做错了什么,如果有人能在这里指导我很感激!
1条答案
按热度按时间emeijp431#
我是这样解决的:
我不确定这是否是最好的解决方案,但现在它的工作,如果有人有任何建议,就如何优化这让我知道。