Add fromunix filter to templates (converts date from UNIX timestamp)
authorMikael Berthe <mikael@lilotux.net>
Sun, 30 Apr 2017 18:43:11 +0200
changeset 41 909c3ddd83f6
parent 40 ad148f60dc87
child 42 7aa54f7e9868
Add fromunix filter to templates (converts date from UNIX timestamp)
printer/plain.go
printer/templateprinter.go
--- a/printer/plain.go	Sun Apr 30 18:17:10 2017 +0200
+++ b/printer/plain.go	Sun Apr 30 18:43:11 2017 +0200
@@ -127,6 +127,19 @@
 	return h // Failed: return initial string
 }
 
+// unix2string convert a UNIX timestamp to a string
+func unix2string(ts interface{}) string {
+	switch t := ts.(type) {
+	case int64:
+		return time.Unix(t, 0).String()
+	case int:
+		return time.Unix(int64(t), 0).String()
+	case float64:
+		return time.Unix(int64(t), 0).String()
+	}
+	return fmt.Sprintf("%v", ts)
+}
+
 func indentedPrint(w io.Writer, indent string, title, skipIfEmpty bool, label string, format string, args ...interface{}) {
 	prefix := indent
 	if title {
@@ -272,7 +285,7 @@
 	indentedPrint(w, indent, true, false, "User token", "%s", s.AccessToken)
 	indentedPrint(w, indent, false, true, "Type", "%s", s.TokenType)
 	if s.CreatedAt != 0 {
-		indentedPrint(w, indent, false, true, "Timestamp", "%v", time.Unix(int64(s.CreatedAt), 0))
+		indentedPrint(w, indent, false, true, "Timestamp", "%v", unix2string(s.CreatedAt))
 	}
 	indentedPrint(w, indent, false, true, "Scope", "%s", s.Scope)
 	return nil
@@ -287,6 +300,6 @@
 	indentedPrint(w, indent, false, false, "Statuses", "%d", is.Statuses)
 	indentedPrint(w, indent, false, false, "Open Registrations", "%v", is.OpenRegistrations)
 	indentedPrint(w, indent, false, false, "Up", "%v", is.Up)
-	indentedPrint(w, indent, false, false, "Date", "%s", time.Unix(is.Date, 0))
+	indentedPrint(w, indent, false, false, "Date", "%s", unix2string(is.Date))
 	return nil
 }
--- a/printer/templateprinter.go	Sun Apr 30 18:17:10 2017 +0200
+++ b/printer/templateprinter.go	Sun Apr 30 18:43:11 2017 +0200
@@ -28,7 +28,10 @@
 // For TemplatePrinter, the option parameter contains the template string.
 func NewPrinterTemplate(option string) (*TemplatePrinter, error) {
 	tmpl := option
-	t, err := template.New("output").Funcs(template.FuncMap{"fromhtml": html2string}).Parse(tmpl)
+	t, err := template.New("output").Funcs(template.FuncMap{
+		"fromhtml": html2string,
+		"fromunix": unix2string,
+	}).Parse(tmpl)
 	if err != nil {
 		return nil, err
 	}