github.com/jxgolibs/go-oauth2-server@v1.0.1/util/time.go (about)

     1  package util
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  // https://golang.org/pkg/time/#pkg-constants
     8  const (
     9  	// RFC3339Mili is a modification of RFC3339Nano to only include ms (3 decimal places)
    10  	RFC3339Mili = "2006-01-02T15:04:05.999Z07:00"
    11  	// DateFormat used for things such as date of birth (when time does not matter)
    12  	DateFormat = "2006-01-02"
    13  )
    14  
    15  // FormatTime formats a time object to RFC3339 with ms precision
    16  func FormatTime(timestamp *time.Time) string {
    17  	if timestamp == nil {
    18  		return ""
    19  	}
    20  	return timestamp.UTC().Format(RFC3339Mili)
    21  }
    22  
    23  // ParseTimestamp parses a string representation of a timestamp in RFC3339
    24  // format and returns a time.Time instance
    25  func ParseTimestamp(timestamp string) (*time.Time, error) {
    26  	// RFC3339 = "2006-01-02T15:04:05Z07:00"
    27  	if timestamp == "" {
    28  		return nil, nil
    29  	}
    30  	t, err := time.Parse(time.RFC3339, timestamp)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  	return &t, nil
    35  }
    36  
    37  // FormatDate formats a time object to a date only format, e.g. 2006-01-02
    38  func FormatDate(timestamp *time.Time) string {
    39  	if timestamp == nil {
    40  		return ""
    41  	}
    42  	return timestamp.UTC().Format(DateFormat)
    43  }
    44  
    45  // ParseDate parses a string representation of a date format
    46  // and returns a time.Time instance
    47  func ParseDate(timestamp string) (*time.Time, error) {
    48  	if timestamp == "" {
    49  		return nil, nil
    50  	}
    51  	t, err := time.Parse(DateFormat, timestamp)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	return &t, nil
    56  }