亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解析 PostgreSQL TIMESTAMP 類型值的問題

解析 PostgreSQL TIMESTAMP 類型值的問題

Go
牧羊人nacy 2023-06-12 15:13:56
在 PostgreSQL 中,我有一個名為surveys.CREATE TABLE SURVEYS(  SURVEY_ID UUID PRIMARY KEY NOT NULL DEFAULT uuid_generate_v4(),  SURVEY_NAME VARCHAR NOT NULL,  SURVEY_DESCRIPTION TEXT,  START_PERIOD TIMESTAMP,  END_PERIOD TIMESTAMP);如您所見,只有SURVEY_ID和SURVEY_NAME列是NOT NULL.在 Go 中,我想根據請求在該表中創建新條目POST。我像這樣發送 JSON 對象:{    "survey_name": "NAME",    "survey_description": "DESCRIPTION",    "start_period": "2019-01-01 00:00:00",    "end_period": "2019-02-28 23:59:59"}不幸是,它引發了奇怪的錯誤:parsing time ""2019-01-01 00:00:00"" as ""2006-01-02T15:04:05Z07:00"": cannot parse " 00:00:00"" as "T"我在哪里犯了錯誤以及如何解決我的問題?模型/surveys.go:import (    "database/sql"    "time")type NullTime struct {    time.Time    Valid bool}type Survey struct {    ID int `json:"survey_id"`    Name string `json:"survey_name"`    Description sql.NullString `json:"survey_description"`    StartPeriod NullTime `json:"start_period"`    EndPeriod NullTime `json:"end_period"`}控制器/surveys.go:var CreateSurvey = func(responseWriter http.ResponseWriter, request *http.Request) {    // Initialize variables.    survey := models.Survey{}    var err error    // The decoder introduces its own buffering and may read data from argument beyond the JSON values requested.    err = json.NewDecoder(request.Body).Decode(&survey)    if err != nil {        log.Println(err)        utils.ResponseWithError(responseWriter, http.StatusInternalServerError, err.Error())        return    }
查看完整描述

1 回答

?
手掌心

TA貢獻1942條經驗 獲得超3個贊

錯誤已經說明出了什么問題:

將時間“2019-01-01 00:00:00”解析為“2006-01-02T15:04:05Z07:00”:無法將“00:00:00”解析為“T”

您正在傳遞"2019-01-01 00:00:00",而它需要不同的時間格式,即RFC3339(UnmarshalJSON 的默認格式)。

要解決這個問題,您要么想要以預期的格式傳遞時間"2019-01-01T00:00:00Z00:00",要么像這樣定義您自己的類型CustomTime

const timeFormat = "2006-01-02 15:04:05"


type CustomTime time.Time


func (ct *CustomTime) UnmarshalJSON(data []byte) error {

? ? newTime, err := time.Parse(timeFormat, strings.Trim(string(data), "\""))

? ? if err != nil {

? ? ? ? return err

? ? }


? ? *ct = CustomTime(newTime)

? ? return nil

}


func (ct *CustomTime) MarshalJSON() ([]byte, error) {

? ? return []byte(fmt.Sprintf("%q", time.Time(*ct).Format(timeFormat))), nil

}

小心,您可能還需要為要在數據庫內外解析的時間實現Valuer和Scanner接口,如下所示:


func (ct CustomTime) Value() (driver.Value, error) {

? ? return time.Time(ct), nil

}


func (ct *CustomTime) Scan(src interface{}) error {

? ? if val, ok := src.(time.Time); ok {

? ? ? ? *ct = CustomTime(val)

? ? } else {

? ? ? ? return errors.New("time Scanner passed a non-time object")

? ? }


? ? return nil

}

去游樂場的例子。



查看完整回答
反對 回復 2023-06-12
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號