You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求协助编写Go语言实现添加分钟并生成时段选项的打印功能

Go实现按日期和频率生成可用时段列表

Got it, let's build this time slot generator step by step. Here's a complete solution that takes a target date and interval (in minutes), then outputs formatted time slots starting from 8:00 AM through to 6:00 PM (easily adjustable if you need different start/end times).

核心思路

  • 先构造目标日期的起始时间(8:00 AM)和结束时间(18:00 PM,可按需修改)
  • 循环从起始时间开始,每次累加指定的分钟间隔,生成每个时段的起止时间
  • 格式化每个时段为HH:MM至HH:MM的字符串格式
  • 返回或打印所有生成的时段

完整代码实现

package main

import (
	"fmt"
	"time"
)

// GenerateTimeSlots 根据指定日期和分钟间隔生成可用时段列表
// 参数:
//   date: 目标日期
//   intervalMinutes: 时段间隔(如30、60)
// 返回: 格式化后的时段字符串切片
func GenerateTimeSlots(date time.Time, intervalMinutes int) []string {
	var slots []string

	// 设置当日的起始时间(8:00 AM)和结束时间(18:00 PM)
	startTime := time.Date(date.Year(), date.Month(), date.Day(), 8, 0, 0, 0, date.Location())
	endTime := time.Date(date.Year(), date.Month(), date.Day(), 18, 0, 0, 0, date.Location())

	// 循环生成每个时段
	currentTime := startTime
	for currentTime.Before(endTime) {
		nextTime := currentTime.Add(time.Duration(intervalMinutes) * time.Minute)
		// 格式化时段字符串:HH:MM至HH:MM
		slot := fmt.Sprintf("%s至%s", currentTime.Format("15:04"), nextTime.Format("15:04"))
		slots = append(slots, slot)
		currentTime = nextTime
	}

	return slots
}

func main() {
	// 示例1:用户选择2024年4月13日,60分钟间隔
	targetDate := time.Date(2024, time.April, 13, 0, 0, 0, 0, time.Local)
	slots60 := GenerateTimeSlots(targetDate, 60)
	fmt.Println("60分钟间隔的可用时段:")
	for _, slot := range slots60 {
		fmt.Printf("- %s\n", slot)
	}

	fmt.Println("\n---")

	// 示例2:用户选择2024年4月13日,30分钟间隔
	slots30 := GenerateTimeSlots(targetDate, 30)
	fmt.Println("30分钟间隔的可用时段:")
	for _, slot := range slots30 {
		fmt.Printf("- %s\n", slot)
	}
}

代码关键点说明

  • 时区处理:使用传入日期的时区(date.Location()),避免跨时区的时间偏差问题
  • 时间格式化:用"15:04"格式字符串,15代表24小时制的小时,04代表两位数字的分钟,完全匹配需求中的显示格式
  • 灵活调整:如果需要修改起始/结束时间,直接调整startTime和endTime的小时参数即可(比如改成9:00 AM开始,19:00 PM结束)
  • 可扩展校验:可以额外添加参数校验逻辑(比如要求intervalMinutes为正整数,且能整除15/30等),避免无效输入导致的异常

运行结果示例

当运行代码后,你会看到类似这样的输出:

60分钟间隔的可用时段:
- 08:00至09:00
- 09:00至10:00
- 10:00至11:00
- 11:00至12:00
- 12:00至13:00
- 13:00至14:00
- 14:00至15:00
- 15:00至16:00
- 16:00至17:00
- 17:00至18:00

---
30分钟间隔的可用时段:
- 08:00至08:30
- 08:30至09:00
- 09:00至09:30
- 09:30至10:00
- 10:00至10:30
- ...(后续时段按30分钟间隔延续至18:00)

内容的提问来源于stack exchange,提问作者TerminatorX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:41:19