github.com/haraldrudell/parl@v0.4.176/short.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  import "time"
     9  
    10  const (
    11  	shortHour         = "060102_15:04:05Z07"
    12  	shortMinute       = "060102_15:04:05Z0700"
    13  	shortHourSpace    = "060102 15:04:05Z07"
    14  	shortMinuteSpace  = "060102 15:04:05Z0700"
    15  	offsetHourDivisor = int(time.Hour / time.Second)
    16  	msHour            = "060102_15:04:05.000Z07"
    17  	msMinute          = "060102_15:04:05.000Z0700"
    18  )
    19  
    20  // Short provides a brief time-stamp in compact second-precision including time-zone.
    21  //   - sample: 060102_15:04:05-08
    22  //   - The timestamp does not contain space.
    23  //   - time zone is what is included in tim, typically time.Local
    24  //   - if tim is not specified, time.Now() in local time zone
    25  func Short(tim ...time.Time) (s string) {
    26  	return timeAndFormat(tim, shortHour, shortMinute)
    27  }
    28  
    29  // Short provides a brief time-stamp in compact second-precision including time-zone.
    30  //   - sample: 060102 15:04:05-08
    31  //   - date is 6-digit separated from time by a space
    32  //   - time zone is what is included in tim, typically time.Local
    33  //   - if tim is not specified, time.Now() in local time zone
    34  func ShortSpace(tim ...time.Time) (s string) {
    35  	return timeAndFormat(tim, shortHourSpace, shortMinuteSpace)
    36  }
    37  
    38  // ShortMs provides a brief time-stamp in compact milli-second-precision including time-zone.
    39  //   - sample: 060102_15:04:05.123-08
    40  //   - The timestamp does not contain space.
    41  //   - time zone is what is included in tim, typically time.Local
    42  //   - if tim is not specified, time.Now() in local time zone
    43  func ShortMs(tim ...time.Time) (s string) {
    44  	return timeAndFormat(tim, msHour, msMinute)
    45  }
    46  
    47  func timeAndFormat(tim []time.Time, hour, minute string) (s string) {
    48  
    49  	// ensure t holds a time
    50  	var t time.Time
    51  	if len(tim) > 0 {
    52  		t = tim[0]
    53  	}
    54  	if t.IsZero() {
    55  		t = time.Now()
    56  	}
    57  
    58  	// pick layout using Zone.offset
    59  	var format string
    60  	if _, offsetS := t.Zone(); offsetS%offsetHourDivisor != 0 {
    61  		format = minute
    62  	} else {
    63  		format = hour
    64  	}
    65  
    66  	return t.Format(format)
    67  }