49 lines
1.2 KiB
Go
Raw Normal View History

2019-09-03 17:34:21 +03:00
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
2019-10-30 19:34:44 +03:00
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
2019-09-03 17:34:21 +03:00
package main
import (
"strconv"
"time"
)
2019-10-17 20:23:45 +03:00
// timestamp stores, formats and automatically prints a timestamp.
2019-09-27 19:09:07 +03:00
type timestamp struct {
2019-10-17 20:23:45 +03:00
// timestamp anonymously embeds a time.
// no need to convert a time value to a timestamp value to use the methods of the time type.
2019-09-27 19:09:07 +03:00
time.Time
}
2019-09-03 17:34:21 +03:00
2019-10-17 20:23:45 +03:00
// String() returns a string representation of timestamp.
// timestamp is an fmt.Stringer.
2019-09-03 17:34:21 +03:00
func (ts timestamp) String() string {
2019-10-17 20:23:45 +03:00
if ts.IsZero() { // same as: ts.Time.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"
2019-10-17 20:23:45 +03:00
return ts.Format(layout) // same as: ts.Time.Format(layout)
2019-09-03 17:34:21 +03:00
}
2019-10-17 20:23:45 +03:00
// toTimestamp returns a timestamp value depending on the type of `v`.
2019-10-17 14:11:51 +03:00
func toTimestamp(v interface{}) (ts timestamp) {
2019-09-03 17:34:21 +03:00
var t int
switch v := v.(type) {
case int:
t = v
case string:
t, _ = strconv.Atoi(v)
}
2019-10-17 14:11:51 +03:00
ts.Time = time.Unix(int64(t), 0)
return ts
2019-09-03 17:34:21 +03:00
}