2016-12-03 113 views
1

我想產生最後的相對3年內隨機時間戳,並將它與這種格式打印出來:%d/%b/%Y:%H:%M:%S %z生成隨機時間戳圍棋

這是我現在所擁有的:

package main 

import (
    "strconv" 
    "time" 
    "math/rand" 
    "fmt" 
) 

func randomTimestamp() time.Time { 
    randomTime := rand.Int63n(time.Now().Unix() - 94608000) + 94608000 

    randomNow, err := time.Parse("10/Oct/2000:13:55:36 -0700", strconv.FormatInt(randomTime, 10)) 
    if err != nil { 
     panic(err) 
    } 

    return randomNow 
} 

func main() { 
    fmt.Println(randomTimestamp().String()) 
} 

這總是拋出:panic: parsing time "...": month out of range。如何爲給定範圍生成隨機時間戳,然後將其轉換爲我想要的標準庫的字符串格式?

回答

1

請勿使用time.Parse。你有一個Unix時間,而不是時間字符串。改爲使用Unix()方法。 https://golang.org/pkg/time/#Unix。您也可以選擇一個最小時間值,比如說1/1/1900,然後在Time中使用Add方法並通過使用Ticks()方法創建的Duration,然後添加一個隨機秒數。 https://golang.org/pkg/time/#Duration

這是一個Go Playground鏈接。請記住Go Playground不支持實際的隨機性。 https://play.golang.org/p/qYTpnbml_N

package main 

import (
    "time" 
    "math/rand" 
    "fmt" 
) 

func randomTimestamp() time.Time { 
    randomTime := rand.Int63n(time.Now().Unix() - 94608000) + 94608000 

    randomNow := time.Unix(randomTime, 0) 

    return randomNow 
} 

func main() { 
    fmt.Println(randomTimestamp().String()) 
} 
+0

啊,這就是我搞砸了,謝謝! – mxplusb