How to get specific time from next day

前端 未结 1 646
小鲜肉
小鲜肉 2021-01-15 13:55

I want to create a time.Time for an exact point in time the following day (tomorrow). For now I would like to set the hour and minute.

This is the code

1条回答
  •  别那么骄傲
    2021-01-15 14:22

    Package time

    import "time" 
    

    The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.


    This is more efficient. It minimizes calls to package time functions and methods.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        now := time.Now()
        fmt.Println(now.Round(0))
        yyyy, mm, dd := now.Date()
        tomorrow := time.Date(yyyy, mm, dd+1, 15, 0, 0, 0, now.Location())
        fmt.Println(tomorrow)
    }
    

    Output:

    2019-06-21 16:23:06.525478162 -0400 EDT
    2019-06-22 15:00:00 -0400 EDT
    

    Some benchmarks:

    BenchmarkNow-8                  31197811            36.6 ns/op
    BenchmarkTomorrowPeterSO-8      29852671            38.4 ns/op
    BenchmarkTomorrowJens-8          9523422           124 ns/op
    

    bench_test.go:

    package main
    
    import (
        "testing"
        "time"
    )
    
    func BenchmarkNow(b *testing.B) {
        for N := 0; N < b.N; N++ {
            now := time.Now()
            _ = now
        }
    }
    
    var now = time.Now()
    
    func BenchmarkTomorrowPeterSO(b *testing.B) {
        for N := 0; N < b.N; N++ {
            // now := time.Now()
            yyyy, mm, dd := now.Date()
            tomorrow := time.Date(yyyy, mm, dd+1, 15, 0, 0, 0, now.Location())
            _ = tomorrow
        }
    }
    
    func BenchmarkTomorrowJens(b *testing.B) {
        for N := 0; N < b.N; N++ {
            // now := time.Now()
            tomorrow := time.Date(now.Year(), now.Month(), now.Day(), 15, 0, 0, 0, now.Location()).AddDate(0, 0, 1)
            _ = tomorrow
        }
    }
    

    0 讨论(0)
提交回复
热议问题