2016-04-12 53 views
1

我需要查詢我的數據庫在一小時內發生的事件。 因此,我想獲得現在然後(現在是 - 24小時,或現在 - 1整天)之間的事件。如何獲得一天前相對於目前的時間?

我試過這種方法,但它是不正確 -

package main 

import (
    "fmt" 
    "time" 
) 

func main() { 

    now := time.Now() 

    // print the time now 
    fmt.Println(now) 

    then := time.Now() 
    diff := 24 
    diff = diff.Hours() 
    then = then.Add(-diff) 

    // print the time before 24 hours 
    fmt.Println(then) 

    // print the delta between 'now' and 'then' 
    fmt.Println(now.Sub(then)) 
} 

我怎樣才能讓然後 == 1整天/前24小時現在

非常感謝您的幫助!

回答

2

使用的時間包中提供的Duration constants,像time.Hour

diff := 24 * time.Hour 
then := time.Now().Add(-diff) 

或者,如果你想在前一天的同一時間(這可能不是在24小時前,http://play.golang.org/p/B32RbtUuuS

then := time.Now().AddDate(0, 0, -1) 
+0

非常感謝!超級有用! – dodiku

相關問題