Projeto bot pontos
This commit is contained in:
54
backend/internal/domain/clock.go
Normal file
54
backend/internal/domain/clock.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ClockTime é um horário do dia (HH:MM), guardado em minutos desde 00:00.
|
||||
type ClockTime int
|
||||
|
||||
func ParseClock(value string) (ClockTime, error) {
|
||||
if len(value) != 5 || value[2] != ':' {
|
||||
return 0, fmt.Errorf("horário inválido %q (use HH:MM)", value)
|
||||
}
|
||||
digits := [4]byte{value[0], value[1], value[3], value[4]}
|
||||
for _, d := range digits {
|
||||
if d < '0' || d > '9' {
|
||||
return 0, fmt.Errorf("horário inválido %q (use HH:MM)", value)
|
||||
}
|
||||
}
|
||||
hour := int(digits[0]-'0')*10 + int(digits[1]-'0')
|
||||
minute := int(digits[2]-'0')*10 + int(digits[3]-'0')
|
||||
if hour > 23 || minute > 59 {
|
||||
return 0, fmt.Errorf("horário inválido %q", value)
|
||||
}
|
||||
return ClockTime(hour*60 + minute), nil
|
||||
}
|
||||
|
||||
func MustParseClock(value string) ClockTime {
|
||||
c, err := ParseClock(value)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c ClockTime) String() string {
|
||||
return fmt.Sprintf("%02d:%02d", int(c)/60, int(c)%60)
|
||||
}
|
||||
|
||||
// On devolve o instante desse horário na data (AAAA-MM-DD) e fuso informados.
|
||||
func (c ClockTime) On(day string, loc *time.Location) time.Time {
|
||||
date, err := time.ParseInLocation(DateLayout, day, loc)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return time.Date(date.Year(), date.Month(), date.Day(), int(c)/60, int(c)%60, 0, 0, loc)
|
||||
}
|
||||
|
||||
// ClockOf devolve o horário do dia de t no fuso informado.
|
||||
func ClockOf(t time.Time, loc *time.Location) ClockTime {
|
||||
local := t.In(loc)
|
||||
return ClockTime(local.Hour()*60 + local.Minute())
|
||||
}
|
||||
Reference in New Issue
Block a user