Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

golang实现获取上一个五分钟整点的时间戳

  1. User

    golang实现获取上一个五分钟整点的时间戳

  2. Assistant

    要实现这个功能,首先获取当前时间,然后将分钟数取整至上一个5的倍数。以下是一个示例实现:

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main() {
    	previousFiveMinute() // call the function
    }
    
    func previousFiveMinute() {
    	now := time.Now()
    	minutes := now.Minute()
    	previous := minutes - (minutes % 5) // 获取上一个五分钟整点的分钟数
    
    	rounded := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), previous, 0, 0, now.Location())
    	roundedTimestamp := rounded.Unix()  // 将上一个五分钟整点的时间转换为 Unix 时间戳
    
    	fmt.Printf("Current time: %v\n", now)
    	fmt.Printf("Last 5 minute boundary: %v\n", rounded)
    	fmt.Printf("Last 5 minute boundary timestamp: %v\n", roundedTimestamp)
    }
    

    运行此代码将显示当前时间,上一个5分钟整点的时间和上一个5分钟整点的Unix时间戳。

    请注意,这个示例可能会有一个问题。当跨小时的时候,这个方法不会自动减少小时数。 如果您需要跨小时的处理,建议在代码中判断previous是否小于0,如果是,则向小时数减1,并将分钟数设置为60 + previous。

    这是一个跨小时处理的示例:

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main() {
    	previousFiveMinute()
    }
    
    func previousFiveMinute() {
    	now := time.Now()
    	minutes := now.Minute()
    	previous := minutes - (minutes % 5)
    
    	year, month, day, hour, loc := now.Year(), now.Month(), now.Day(), now.Hour(), now.Location()
    	// 如果 previous 小于 0 ,则减少一小时,并设置分钟数为 60 + previous
    	if previous < 0 {
    		previous += 60
    		hour -= 1
    	}
    
    	rounded := time.Date(year, month, day, hour, previous, 0, 0, loc)
    	roundedTimestamp := rounded.Unix()
    
    	fmt.Printf("Current time: %v\n", now)
    	fmt.Printf("Last 5 minute boundary: %v\n", rounded)
    	fmt.Printf("Last 5 minute boundary timestamp: %v\n", roundedTimestamp)
    }
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.