-3

When I marshall time.Now() to JSON object it gives result as "2009-11-10T23:00:00Z" but printing time.Now gives 2009-11-10 23:00:00 +0000 UTC. Why are they different. What are T and Z. Also how can I convert it to swift NSDate object according to this table?

Thellimist
  • 3,757
  • 5
  • 31
  • 49

1 Answers1

0

The meaning of those values is irrelevant, they're part of that format (ISO8601). There are a couple approaches to this. One is to define a custom MarshalJSON() method for time or your struct and use it to format the date, the other is to represent it as a string in your struct in the first place so that when the default implementation executes you get the result you're looking for.

The method you'll ultimately need to use is; time.Format(format string) The golang docs show this example for using it;

package main

import (
    "fmt"
    "time"
)

func main() {
    // layout shows by example how the reference time should be represented.
    const layout = "Jan 2, 2006 at 3:04pm (MST)"
    t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
    fmt.Println(t.Format(layout))
    fmt.Println(t.UTC().Format(layout))
}

The medium date format in that link for example would use the string "Jan. 2, 2006"

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • But why is the marshalled time and the printed time different? – Thellimist Jul 23 '15 at 22:00
  • 1
    @Thellimist because when marshal the json, the package uses reflection to iterate the types properties and format them for json. The a `time.Date` is formatted it's using the default format string. What I was trying to explain is that you can either avoid that by using a string in the struct you marshal, or you can implement that method so that when the `time.Date` is formatted it's using one of the ones you need. – evanmcdonnal Jul 23 '15 at 22:22
  • I understood your answer. I was wondering why they were different also. Wish I had asked as a separate question :) While reflection why doesn't it converts as a default format string – Thellimist Jul 23 '15 at 22:26