github.com/gogf/gf@v1.16.9/util/gconv/gconv_time.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). 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/gogf/gf.
     6  
     7  package gconv
     8  
     9  import (
    10  	"time"
    11  
    12  	"github.com/gogf/gf/internal/utils"
    13  	"github.com/gogf/gf/os/gtime"
    14  )
    15  
    16  // Time converts `any` to time.Time.
    17  func Time(any interface{}, format ...string) time.Time {
    18  	// It's already this type.
    19  	if len(format) == 0 {
    20  		if v, ok := any.(time.Time); ok {
    21  			return v
    22  		}
    23  	}
    24  	if t := GTime(any, format...); t != nil {
    25  		return t.Time
    26  	}
    27  	return time.Time{}
    28  }
    29  
    30  // Duration converts `any` to time.Duration.
    31  // If `any` is string, then it uses time.ParseDuration to convert it.
    32  // If `any` is numeric, then it converts `any` as nanoseconds.
    33  func Duration(any interface{}) time.Duration {
    34  	// It's already this type.
    35  	if v, ok := any.(time.Duration); ok {
    36  		return v
    37  	}
    38  	s := String(any)
    39  	if !utils.IsNumeric(s) {
    40  		d, _ := gtime.ParseDuration(s)
    41  		return d
    42  	}
    43  	return time.Duration(Int64(any))
    44  }
    45  
    46  // GTime converts `any` to *gtime.Time.
    47  // The parameter `format` can be used to specify the format of `any`.
    48  // If no `format` given, it converts `any` using gtime.NewFromTimeStamp if `any` is numeric,
    49  // or using gtime.StrToTime if `any` is string.
    50  func GTime(any interface{}, format ...string) *gtime.Time {
    51  	if any == nil {
    52  		return nil
    53  	}
    54  	if v, ok := any.(apiGTime); ok {
    55  		return v.GTime(format...)
    56  	}
    57  	// It's already this type.
    58  	if len(format) == 0 {
    59  		if v, ok := any.(*gtime.Time); ok {
    60  			return v
    61  		}
    62  		if t, ok := any.(time.Time); ok {
    63  			return gtime.New(t)
    64  		}
    65  		if t, ok := any.(*time.Time); ok {
    66  			return gtime.New(t)
    67  		}
    68  	}
    69  	s := String(any)
    70  	if len(s) == 0 {
    71  		return gtime.New()
    72  	}
    73  	// Priority conversion using given format.
    74  	if len(format) > 0 {
    75  		t, _ := gtime.StrToTimeFormat(s, format[0])
    76  		return t
    77  	}
    78  	if utils.IsNumeric(s) {
    79  		return gtime.NewFromTimeStamp(Int64(s))
    80  	} else {
    81  		t, _ := gtime.StrToTime(s)
    82  		return t
    83  	}
    84  }