github.com/divyam234/rclone@v1.64.1/fs/parsetime.go (about)

     1  package fs
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"time"
     7  )
     8  
     9  // Time is a time.Time with some more parsing options
    10  type Time time.Time
    11  
    12  // For overriding in unittests.
    13  var (
    14  	timeNowFunc = time.Now
    15  )
    16  
    17  // Turn Time into a string
    18  func (t Time) String() string {
    19  	if !t.IsSet() {
    20  		return "off"
    21  	}
    22  	return time.Time(t).Format(time.RFC3339Nano)
    23  }
    24  
    25  // IsSet returns if the time is not zero
    26  func (t Time) IsSet() bool {
    27  	return !time.Time(t).IsZero()
    28  }
    29  
    30  // ParseTime parses a time or duration string as a Time.
    31  func ParseTime(date string) (t time.Time, err error) {
    32  	if date == "off" {
    33  		return time.Time{}, nil
    34  	}
    35  
    36  	now := timeNowFunc()
    37  
    38  	// Attempt to parse as a text time
    39  	t, err = parseTimeDates(date)
    40  	if err == nil {
    41  		return t, nil
    42  	}
    43  
    44  	// Attempt to parse as a time.Duration offset from now
    45  	d, err := time.ParseDuration(date)
    46  	if err == nil {
    47  		return now.Add(-d), nil
    48  	}
    49  
    50  	d, err = parseDurationSuffixes(date)
    51  	if err == nil {
    52  		return now.Add(-d), nil
    53  	}
    54  
    55  	return t, err
    56  }
    57  
    58  // Set a Time
    59  func (t *Time) Set(s string) error {
    60  	parsedTime, err := ParseTime(s)
    61  	if err != nil {
    62  		return err
    63  	}
    64  	*t = Time(parsedTime)
    65  	return nil
    66  }
    67  
    68  // Type of the value
    69  func (t Time) Type() string {
    70  	return "Time"
    71  }
    72  
    73  // UnmarshalJSON makes sure the value can be parsed as a string in JSON
    74  func (t *Time) UnmarshalJSON(in []byte) error {
    75  	var s string
    76  	err := json.Unmarshal(in, &s)
    77  	if err != nil {
    78  		return err
    79  	}
    80  
    81  	return t.Set(s)
    82  }
    83  
    84  // MarshalJSON marshals as a time.Time value
    85  func (t Time) MarshalJSON() ([]byte, error) {
    86  	return json.Marshal(time.Time(t))
    87  }
    88  
    89  // Scan implements the fmt.Scanner interface
    90  func (t *Time) Scan(s fmt.ScanState, ch rune) error {
    91  	token, err := s.Token(true, func(rune) bool { return true })
    92  	if err != nil {
    93  		return err
    94  	}
    95  	return t.Set(string(token))
    96  }