簡體   English   中英

如何將 YYYY-MM-DD 字符串格式轉換為 Golang 中的時間戳?

[英]How to convert YYYY-MM-DD string format to timestamp in Golang?

如果這是一個微不足道的問題,我很抱歉。 這是我目前所擁有的。

    snapshot = "2017-07-25"
    snapshotFilter := " AND cdate = %s"
    snapshot, err := time.Parse(time.RFC3339, snapshot)
    if err != nil {
        log.Fatal(err)
    }
    queryFilter = queryFilter + fmt.Sprintf(snapshotFilter, pq.FormatTimestamp(snapshot))

這是輸出

2017/09/12 09:59:34 parsing time "2017-07-25" as "2006-01-02T15:04:05Z07:": cannot parse "" as "T".

我正在嘗試以正確的格式獲取snapshot以將其插入到 postgres 查詢中。

我正在使用

"database/sql"
"time"
"github.com/gorilla/mux"
"github.com/lib/pq"

編輯:似乎這更多是 postgres 的問題,而2017-07-25只需要放在引號中並放在 postgres 查詢字符串中。

正如已經建議的那樣,使用這個:

package main

import (
    "fmt"
    "log"
    "time"
)

const layout = "2006-01-02"

func main() {
    snapshot := "2017-07-25"
    t, err := time.Parse(layout, snapshot)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(t)
}

正如您在 time 包的常量文檔中看到的那樣,有一個參考日期

Layout      = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.

用於指定日期/時間字符串布局。 因此,您提供一個字符串,並且每次出現的3都會被您的時間點的 12h am/pm 符號中的小時替換,並且每次出現的15都會被替換為 24h 表示中的小時。

文檔中的一些示例代碼解釋了這種方法的所有問題和問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM