dpk20361 2016-08-04 19:02
浏览 257
已采纳

Golang日期时间结构

I'm trying to build golang date time struct and I'm having some issues. Please help me build the model.

Thanks again

 "effectiveDates" : {
    "startDate" : {
        "_class" : "com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl", 
        "year" : NumberInt(2008), 
        "month" : NumberInt(10), 
        "day" : NumberInt(16), 
        "timezone" : NumberInt(-300), 
        "hour" : NumberInt(9), 
        "minute" : NumberInt(50), 
        "second" : NumberInt(13)
    }
}
  • 写回答

1条回答 默认 最新

  • douhuan3420 2016-08-05 03:22
    关注

    This should be enough to get you going. There are a couple quirks:

    • The NumberInt(n) values are not valid JSON, so I've assumed they come in from the GET call as a number
    • The timezone NumberInt will need to be converted to a string, and massaged into the form -0700. I've left that as an exercise for you

    Here's my solution:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "time"
    )
    
    type StartDate struct {
        Class    string `json:"_class"`
        Year     int `json:"year"`
        Month    int `json:"month"`
        Day      int `json:"day"`
        Timezone string `json:"timezone"`
        Hour     int `json:"hour"`
        Minute   int `json:"minute"`
        Second   int `json:"second"`
    }
    
    type EffectiveDates struct {
        StartDate `json:"startDate"`
    }
    
    type Payload struct {
        EffectiveDates `json:"effectiveDates"`
    }
    
    var input = `{ 
      "effectiveDates" : {
         "startDate" : {
            "_class" : "com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl", 
            "year" : 2008, 
            "month" : 10, 
            "day" : 16, 
            "timezone" : "-0300", 
            "hour" : 9, 
            "minute" : 50, 
            "second" : 13
         }
      }
    }`
    
    func main() {
        var p Payload
        var t time.Time
        err := json.Unmarshal([]byte(input[:]), &p)
        if err != nil {
            fmt.Println("error:", err)
        }
        timeStr := fmt.Sprintf("%d-%d-%d %d:%d:%d %s", p.Year, p.Month, p.Day, p.Hour, p.Minute, p.Second, p.Timezone)
        if t, err = time.Parse("2006-01-02 3:04:05 -0700", timeStr); err != nil {
            fmt.Println("error:", err)
        }
        fmt.Printf("%s", t.Format(time.RFC3339))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算