Skip to content

Instantly share code, notes, and snippets.

@vaguecoder
Last active May 21, 2021 19:10
Show Gist options
  • Save vaguecoder/5402cadf0707afbbfccc0e0c3abb650a to your computer and use it in GitHub Desktop.
Save vaguecoder/5402cadf0707afbbfccc0e0c3abb650a to your computer and use it in GitHub Desktop.
Overrides the marshaller function to marshal time.Time object to a specific formatted time string, similar to: "21-May-2021 23:20:08 IST". More details in: https://github.com/VagueCoder/Random-Go-Snippets/
package formattedTime
import (
"fmt"
"regexp"
"time"
)
type FormattedTime string
func (f *FormattedTime) MarshalJSON() ([]byte, error) {
// Curtom regex as per timr string . Eg.: "2021-05-21 23:15:46.3598134 +0530 IST m=+0.000204301"
pattern := regexp.MustCompile(`\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{7} [-+]\d{4} [A-Z]{3}`)
// Extract & validate part of time string to parse
b := pattern.Find([]byte(fmt.Sprint(*f)))
if len(b) == 0 {
return []byte(""), fmt.Errorf("Error at Regex Match: Couldn't find time string in pattern XXXX-XX-XX XX:XX:XX")
}
// Parse time string int time.Time object
t, err := time.Parse("2006-01-02 15:04:05.0000000 -0700 MST", string(b))
if err != nil {
return []byte(""), fmt.Errorf("Error at FormattedTime Marshal: %v", err)
}
// Again, format time.Time object into required time format
timeString := fmt.Sprintf("%q", t.Format("02-Jan-2006 15:04:05 MST"))
return []byte(timeString), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment