54 lines
1.2 KiB
Go
Raw Normal View History

2019-09-03 17:34:21 +03:00
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"strconv"
"time"
)
2019-09-27 19:09:07 +03:00
// timestamp stores, formats and automatically prints a timestamp: it's a stringer.
type timestamp struct {
// timestamp embeds a time, therefore it can be used as a time value.
// there is no need to convert a time value to a timestamp value.
time.Time
}
2019-09-03 17:34:21 +03:00
2019-09-27 19:09:07 +03:00
// String method makes the timestamp an fmt.stringer.
2019-09-03 17:34:21 +03:00
func (ts timestamp) String() string {
2019-09-27 19:09:07 +03:00
if ts.IsZero() {
2019-09-03 17:34:21 +03:00
return "unknown"
}
2019-09-27 19:09:07 +03:00
// Mon Jan 2 15:04:05 -0700 MST 2006
const layout = "2006/01"
return ts.Format(layout)
2019-09-03 17:34:21 +03:00
}
2019-09-27 19:09:07 +03:00
// toTimestamp returns a timestamp value depending on the type of `v`.
// toTimestamp was "book.format()" before.
2019-09-03 17:34:21 +03:00
func toTimestamp(v interface{}) timestamp {
var t int
switch v := v.(type) {
case int:
2019-09-27 19:09:07 +03:00
// book{title: "moby dick", price: 10, published: 118281600},
2019-09-03 17:34:21 +03:00
t = v
case string:
2019-09-27 19:09:07 +03:00
// book{title: "odyssey", price: 15, published: "733622400"},
2019-09-03 17:34:21 +03:00
t, _ = strconv.Atoi(v)
default:
2019-09-27 19:09:07 +03:00
// book{title: "hobbit", price: 25},
return timestamp{}
2019-09-03 17:34:21 +03:00
}
2019-09-27 19:09:07 +03:00
return timestamp{
Time: time.Unix(int64(t), 0),
}
2019-09-03 17:34:21 +03:00
}