gopkg.in/easygen.v4@v4.1.0/tf-datetime.go (about)

     1  package easygen
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"time"
     7  )
     8  
     9  // now is function that represents the current time in UTC. This is here
    10  // primarily for the tests to override times.
    11  var now = func() time.Time { return time.Now() }
    12  
    13  //==========================================================================
    14  // template function for date & time
    15  
    16  // https://godoc.org/time#pkg-constants
    17  
    18  // date returns the date or year
    19  func date(fmt string) string {
    20  	switch fmt {
    21  	case "Y4":
    22  		// returns the year string of length 4
    23  		return time.Now().Format("2006")
    24  	case "I":
    25  		// returns the output of `date -I`
    26  		return time.Now().Format("2006-01-02")
    27  		// for the output of `date -Iseconds`
    28  		// use `timestamp`
    29  	default:
    30  		return time.Now().Format("2006" + fmt + "01" + fmt + "02")
    31  	}
    32  }
    33  
    34  // https://github.com/hashicorp/consul-template/blob/de2ebf4/template_functions.go#L666-L682
    35  
    36  // timestamp returns the current UNIX timestamp in UTC. If an argument is
    37  // specified, it will be used to format the timestamp.
    38  func timestamp(s ...string) (string, error) {
    39  	switch len(s) {
    40  	case 0:
    41  		return now().Format(time.RFC3339), nil
    42  	case 1:
    43  		if s[0] == "unix" {
    44  			return strconv.FormatInt(now().Unix(), 10), nil
    45  		}
    46  		return now().Format(s[0]), nil
    47  	default:
    48  		return "", fmt.Errorf("timestamp: wrong number of arguments, expected 0 or 1"+
    49  			", but got %d", len(s))
    50  	}
    51  }