github.com/polarismesh/polaris@v1.17.8/common/time/time.go (about) 1 /** 2 * Tencent is pleased to support the open source community by making Polaris available. 3 * 4 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. 5 * 6 * Licensed under the BSD 3-Clause License (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * https://opensource.org/licenses/BSD-3-Clause 11 * 12 * Unless required by applicable law or agreed to in writing, software distributed 13 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 * specific language governing permissions and limitations under the License. 16 */ 17 18 package time 19 20 import ( 21 "encoding/json" 22 "errors" 23 "syscall" 24 "time" 25 ) 26 27 // CurrentMillisecond 获取低精度的微秒时间 28 func CurrentMillisecond() int64 { 29 var tv syscall.Timeval 30 if err := syscall.Gettimeofday(&tv); err != nil { 31 return time.Now().UnixNano() / 1e6 32 } 33 return int64(tv.Sec)*1e3 + int64(tv.Usec)/1e3 34 } 35 36 // Duration duration alias 37 type Duration time.Duration 38 39 // MarshalJSON marshal duration to json 40 func (d Duration) MarshalJSON() ([]byte, error) { 41 return json.Marshal(time.Duration(d).String()) 42 } 43 44 // UnmarshalJSON unmarshal json text to struct 45 func (d *Duration) UnmarshalJSON(b []byte) error { 46 var v interface{} 47 if err := json.Unmarshal(b, &v); err != nil { 48 return err 49 } 50 switch value := v.(type) { 51 case float64: 52 *d = Duration(time.Duration(value)) 53 return nil 54 case string: 55 tmp, err := time.ParseDuration(value) 56 if err != nil { 57 return err 58 } 59 *d = Duration(tmp) 60 return nil 61 default: 62 return errors.New("invalid duration") 63 } 64 } 65 66 // Time2String Convert time.Time to string time 67 func Time2String(t time.Time) string { 68 return t.Format("2006-01-02 15:04:05") 69 } 70 71 // Int64Time2String Convert time stamp of Int64 to string time 72 func Int64Time2String(t int64) string { 73 return time.Unix(t, 0).Format("2006-01-02 15:04:05") 74 }