github.com/wtfutil/wtf@v0.43.0/modules/clocks/clock.go (about)

     1  package clocks
     2  
     3  import (
     4  	"strings"
     5  	"time"
     6  )
     7  
     8  type Clock struct {
     9  	Label    string
    10  	Location *time.Location
    11  }
    12  
    13  func NewClock(label string, timeLoc *time.Location) Clock {
    14  	clock := Clock{
    15  		Label:    label,
    16  		Location: timeLoc,
    17  	}
    18  
    19  	return clock
    20  }
    21  
    22  func BuildClock(label string, location string) (clock Clock, err error) {
    23  	timeLoc, err := time.LoadLocation(sanitizeLocation(location))
    24  	if err != nil {
    25  		return Clock{}, err
    26  	}
    27  	return NewClock(label, timeLoc), nil
    28  }
    29  
    30  func (clock *Clock) Date(dateFormat string) string {
    31  	return clock.LocalTime().Format(dateFormat)
    32  }
    33  
    34  func (clock *Clock) LocalTime() time.Time {
    35  	return clock.ToLocal(time.Now())
    36  }
    37  
    38  func (clock *Clock) ToLocal(t time.Time) time.Time {
    39  	return t.In(clock.Location)
    40  }
    41  
    42  func (clock *Clock) Time(timeFormat string) string {
    43  	return clock.LocalTime().Format(timeFormat)
    44  }
    45  
    46  func sanitizeLocation(locStr string) string {
    47  	return strings.ReplaceAll(locStr, " ", "_")
    48  }