go-force icon indicating copy to clipboard operation
go-force copied to clipboard

Salesforce Date/Time into Golang time.Time

Open gmark-newt opened this issue 9 years ago • 3 comments

Is there any way to easily read back a Salesforce Date/Time object into a golang time.Time object?

I can write a Golang time.Time object into the Salesforce Date/Time object, but I cannot go the other way. I get this error: "Unable to unmarshal response to object: parsing time ""1965-04-06T00:00:00.000+0000"" as ""2006-01-02T15:04:05Z07:00"": cannot parse "+0000"" as "Z07:00"1"

How can I achieve this? Thanks!

gmark-newt avatar Sep 02 '16 20:09 gmark-newt

@gmark-newt You can create a type that implements the json.Marshaler and json.Unmarshaler interfaces.

Warning untested code ahead!

const SFTIMEFORMAT = "2006-01-02T15:04:05.000-0700"

type SFTime struct {
    time.Time
}

// MarshalJSON implements the json.Marshaler interface.
// The time is a quoted string in Salesforce time format.
func (t SFTime) MarshalJSON() ([]byte, error) {
    b := make([]byte, 0, len(SFTIMEFORMAT)+2)
    b = append(b, '"')
    b = t.AppendFormat(b, SFTIMEFORMAT)
    b = append(b, '"')
    return b, nil
}

// UnmarshalJSON implements the json.Unmarshaler interface.
// The time is expected to be a quoted string in Salesforce time format.
func (t *SFTime) UnmarshalJSON(data []byte) error {
    internalTime, err := time.Parse(`"`+SFTIMEFORMAT+`"`, string(data))
    if err != nil {
        return err
    }

    *t = SFTime{internalTime}
    return nil
}

nimajalali avatar Sep 16 '16 08:09 nimajalali

@nimajalali if I submitted a patch to add a Date type to sobjects and change the type of built-in fields like CreatedDate and LastModifiedDate to the new type, do you think such a patch would be accepted?

dragonsinth avatar Apr 29 '19 20:04 dragonsinth

#62

dragonsinth avatar Apr 30 '19 17:04 dragonsinth