Commits

Miki Tebeka committed 8d2604b

Documentation

Comments (0)

Files changed (2)

+package jtime
+
+/* Package jtime provides flexible JSON time.Time marshing/unmarshaling
+
+How it works?
+
+Use jtime.Time in your struct, and before calling json.Marshal/json.Unmarashal
+set the marshaller using SetMarshaller.
+
+You can either write your own marshaller or use two of the available marshallers:
+* FormatMashaller uses time.Time format to marshal/unmarshal time as JSON strings
+* UnixMarshaler marshal time.Time to JSON integers (with or without msec)
+
+jtime.Time embeds time.Time so you can use all time.Time methods with it.
+
+Example:
+
+	package main
+
+	import (
+		"encoding/json"
+		"fmt"
+		"log"
+
+		"bitbucket.org/tebeka/jtime"
+	)
+
+	type T struct {
+		Created jtime.Time `json:"created"`
+	}
+
+	func main() {
+		jtime.SetMarshaler(&jtime.UnixMarshaler{})
+		data := []byte(`{"created":1382135725}`) // Oct 18, 2013
+		t := T{}
+		if err := json.Unmarshal(data, &t); err != nil {
+			log.Fatalf("error umarshaling: %s\n", err)
+		}
+		fmt.Println(t.Created)
+	}
+
+Caution: Changing marshaller in mid-flight is dangerous :)
+*/
 	"time"
 )
 
+// Time structure, embeds time.Time
 type Time struct {
 	time.Time
 }
 
+// Marshler interface for marshaling/umarshaling time
 type Marshaler interface {
 	Marshal(t Time) ([]byte, error)
 	Unmarshal(data []byte) (Time, error)
 
 var marshaler Marshaler
 
+// SetMarshaler sets the current marshaller
 func SetMarshaler(m Marshaler) {
 	marshaler = m
 }
 
+// FormatMashaler uses time.Time format strings
 type FormatMashaler struct {
 	Format string
 }
 
+// Marshal will marshal to JSON string in Format
 func (fm *FormatMashaler) Marshal(t Time) ([]byte, error) {
 	return []byte(`"` + t.Format(fm.Format) + `"`), nil
 }
 
+// Unmarshal from JSON string in Format
 func (fm *FormatMashaler) Unmarshal(data []byte) (Time, error) {
 	if len(data) < 2 {
 		return Time{}, fmt.Errorf("data too short - %v", data)
 	return Time{t}, err
 }
 
+// UnixMarshaler uses integers as format
 type UnixMarshaler struct {
-	MSec bool
+	MSec bool // Time in millseconds
 }
 
+// Marashal to JSON integer
 func (um *UnixMarshaler) Marshal(t Time) ([]byte, error) {
 	data := fmt.Sprintf("%d", t.Unix())
 	if um.MSec {
 	return []byte(data), nil
 }
 
+// Unmarshal from JSON integer
 func (um *UnixMarshaler) Unmarshal(data []byte) (Time, error) {
 	sec, err := strconv.ParseInt(string(data), 10, 64)
 	if err != nil {