github.com/decred/dcrlnd@v0.7.6/cmd/dcrlncli/arg_parse.go (about)

     1  package main
     2  
     3  import (
     4  	"regexp"
     5  	"strconv"
     6  	"time"
     7  )
     8  
     9  // reTimeRange matches systemd.time-like short negative timeranges, e.g. "-200s".
    10  var reTimeRange = regexp.MustCompile(`^-\d{1,18}[s|m|h|d|w|M|y]$`)
    11  
    12  // secondsPer allows translating s(seconds), m(minutes), h(ours), d(ays),
    13  // w(eeks), M(onths) and y(ears) into corresponding seconds.
    14  var secondsPer = map[string]int64{
    15  	"s": 1,
    16  	"m": 60,
    17  	"h": 3600,
    18  	"d": 86400,
    19  	"w": 604800,
    20  	"M": 2630016,  // 30.44 days
    21  	"y": 31557600, // 365.25 days
    22  }
    23  
    24  // parseTime parses UNIX timestamps or short timeranges inspired by sytemd (when starting with "-"),
    25  // e.g. "-1M" for one month (30.44 days) ago.
    26  func parseTime(s string, base time.Time) (uint64, error) {
    27  	if reTimeRange.MatchString(s) {
    28  		last := len(s) - 1
    29  
    30  		d, err := strconv.ParseInt(s[1:last], 10, 64)
    31  		if err != nil {
    32  			return uint64(0), err
    33  		}
    34  
    35  		mul := secondsPer[string(s[last])]
    36  		return uint64(base.Unix() - d*mul), nil
    37  	}
    38  
    39  	return strconv.ParseUint(s, 10, 64)
    40  }