github.com/zhongdalu/gf@v1.0.0/g/util/gconv/gconv_time.go (about) 1 // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 package gconv 8 9 import ( 10 "time" 11 12 "github.com/zhongdalu/gf/g/internal/strutils" 13 "github.com/zhongdalu/gf/g/os/gtime" 14 ) 15 16 // Time converts <i> to time.Time. 17 func Time(i interface{}, format ...string) time.Time { 18 if t := GTime(i, format...); t != nil { 19 return t.Time 20 } 21 return time.Time{} 22 } 23 24 // Duration converts <i> to time.Duration. 25 // If <i> is string, then it uses time.ParseDuration to convert it. 26 // If <i> is numeric, then it converts <i> as nanoseconds. 27 func Duration(i interface{}) time.Duration { 28 s := String(i) 29 if !strutils.IsNumeric(s) { 30 d, _ := time.ParseDuration(s) 31 return d 32 } 33 return time.Duration(Int64(i)) 34 } 35 36 // GTime converts <i> to *gtime.Time. 37 // The parameter <format> can be used to specify the format of <i>. 38 // If no <format> given, it converts <i> using gtime.NewFromTimeStamp if <i> is numeric, 39 // or using gtime.StrToTime if <i> is string. 40 func GTime(i interface{}, format ...string) *gtime.Time { 41 s := String(i) 42 if len(s) == 0 { 43 return gtime.New() 44 } 45 // Priority conversion using given format. 46 if len(format) > 0 { 47 t, _ := gtime.StrToTimeFormat(s, format[0]) 48 return t 49 } 50 if strutils.IsNumeric(s) { 51 return gtime.NewFromTimeStamp(Int64(s)) 52 } else { 53 t, _ := gtime.StrToTime(s) 54 return t 55 } 56 }