golangデータ取得時間からフレンドリーな時間処理

874 ワード

ダイレクトコード
FriendlyTime.go
package tools

import (
	"fmt"
	"math"
	"time"
)

// Custom format friendly time
type FriendlyTime string

// Scan value of time.Time
func (t *FriendlyTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		var tmpStr string
		nowTime := GetNowTime()
		// second
		diffTime := nowTime.Unix() - value.Unix()
		//       
		switch {
		case diffTime <= 0:
			tmpStr = "  "
		case diffTime <= 60:
			tmpStr = fmt.Sprintf("%d  ", diffTime)
		case diffTime <= 3600:
			tmpStr = fmt.Sprintf("%.0f   ", math.Ceil(float64(diffTime/60)))
		case diffTime <= 86400:
			tmpStr = fmt.Sprintf("%.0f   ", math.Ceil(float64(diffTime/60/60)))
		default:
			// cur year
			if nowTime.Year() == value.Year() {
				tmpStr = value.Format("01-02 15:04"