github.com/0chain/gosdk@v1.17.11/core/common/time.go (about)

     1  package common
     2  
     3  import (
     4  	"errors"
     5  	"strconv"
     6  	"strings"
     7  	"time"
     8  )
     9  
    10  // Timestamp represents Unix time (e.g. in seconds)
    11  type Timestamp int64
    12  
    13  // Now current datetime
    14  func Now() Timestamp {
    15  	return Timestamp(time.Now().Unix())
    16  }
    17  
    18  // Within ensures a given timestamp is within certain number of seconds
    19  func (t Timestamp) Within(seconds Timestamp) bool {
    20  	var now = Now()
    21  	return now > t-seconds && now < t+seconds
    22  }
    23  
    24  // ToTime converts the Timestamp to standard time.Time
    25  func (t Timestamp) ToTime() time.Time {
    26  	return time.Unix(int64(t), 0)
    27  }
    28  
    29  var ErrInvalidTime = errors.New("invalid time")
    30  
    31  // ParseTime parse a time string with 4 formats
    32  //
    33  //	+1h5m : now (local timezone) + 1h5m
    34  //	+3900 : now (local timezone) +3900s
    35  //	1647858200 : Unix timestamp
    36  //	2022-03-21 10:21:38 : parse UTC date string with YYYY-MM-dd HH:mm:ss
    37  //
    38  // Parameters
    39  //   - now is the current time
    40  //   - input is the time string to parse
    41  func ParseTime(now time.Time, input string) (*time.Time, error) {
    42  
    43  	if len(input) == 0 {
    44  		return nil, ErrInvalidTime
    45  	}
    46  
    47  	if input[0] == '+' {
    48  		val := strings.TrimLeft(input, "+")
    49  		s, err := strconv.Atoi(val)
    50  		// +3900 : now (local timezone) +3900s
    51  		if err == nil {
    52  			now = now.Add(time.Duration(s) * time.Second)
    53  			return &now, nil
    54  		}
    55  
    56  		d, err := time.ParseDuration(val)
    57  		// +1h5m : now (local timezone) + 1h5m
    58  		if err == nil {
    59  			now = now.Add(d)
    60  			return &now, nil
    61  		}
    62  
    63  		return nil, ErrInvalidTime
    64  	}
    65  
    66  	s, err := strconv.ParseInt(input, 10, 64)
    67  	if err == nil {
    68  		now = time.Unix(s, 0)
    69  		return &now, nil
    70  	}
    71  
    72  	// 2022-03-21 10:21:38 : parse UTC date string with YYYY-MM-dd HH:mm:ss
    73  	t, err := time.Parse("2006-01-02 15:04:05 -0700", input+" +0000")
    74  	if err == nil {
    75  		return &t, nil
    76  	}
    77  
    78  	return nil, ErrInvalidTime
    79  
    80  }