package protocol

import (
	"time"
)

var beijingtz *time.Location

func init() {
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		beijingtz = time.FixedZone("CST", 8*3600)
	} else {
		beijingtz = loc
	}
}
func BJNow() time.Time {
	return time.Now().In(beijingtz)
}
func ToBJTime(t time.Time) time.Time {
	return t.In(beijingtz)
}

type BJTime time.Time

const (
	timeFormart = "2006-01-02 15:04:05"
)

func (t *BJTime) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), beijingtz)
	*t = BJTime(now)
	return
}

func (t BJTime) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(timeFormart)+2)
	b = append(b, '"')
	tt := time.Time(t)
	if !tt.IsZero() {
		b = tt.AppendFormat(b, timeFormart)
	}
	b = append(b, '"')
	return b, nil
}

func (t BJTime) String() string {
	tt := time.Time(t)
	if tt.IsZero() {
		return ""
	}
	return tt.Format(timeFormart)
}
