Skip to content

Instantly share code, notes, and snippets.

@rossnelson
Last active February 21, 2024 18:41
Show Gist options
  • Save rossnelson/93b96e1fedb08fd7970b1ba782437279 to your computer and use it in GitHub Desktop.
Save rossnelson/93b96e1fedb08fd7970b1ba782437279 to your computer and use it in GitHub Desktop.
package intervals
var names = map[string]string{
"daily": "daily",
"weekly": "weekly",
"monthly": "monthly",
"yearly": "yearly",
}
var singular = map[string]string{
"daily": "day",
"weekly": "week",
"monthly": "month",
"yearly": "year",
}
func Name(interval string) string {
return names[interval]
}
func Singular(interval string) string {
return singular[interval]
}
package ranges
import (
"fmt"
"time"
)
type Params struct {
interval string
Start string `db:"start"`
End string `db:"end"`
}
func New(interval string) *Params {
return &Params{interval: interval}
}
func (r *Params) AsRange() *Params {
currentTime := time.Now()
r.End = currentTime.Format("2006-01-02")
previousTime := time.Now()
switch r.interval {
// daily - last 24 hours
case "daily":
previousTime = currentTime.Add(-time.Hour * 24)
fmt.Println(previousTime)
// weekly - last 7 days
case "weekly":
previousTime = currentTime.AddDate(0, 0, -7)
// weekly - last 1 month
case "monthly":
currentYear, currentMonth, _ := currentTime.Date()
currentLocation := currentTime.Location()
firstOfMonth := time.Date(
currentYear, currentMonth, 1, 0, 0, 0, 0, currentLocation,
)
previousTime = firstOfMonth
// yearly - last 1 year
case "yearly":
currentYear, _, _ := currentTime.Date()
currentLocation := currentTime.Location()
firstOfYear := time.Date(
currentYear, 1, 1, 0, 0, 0, 0, currentLocation,
)
previousTime = firstOfYear
}
r.Start = previousTime.Format("2006-01-02")
return r
}
func (r *Params) AsHistogram() *Params {
currentTime := time.Now()
r.End = currentTime.Format("2006-01-02")
previousTime := time.Now()
switch r.interval {
// daily - last 7 days
case "daily":
previousTime = currentTime.AddDate(0, 0, -7)
// weekly - last 4 weeks
case "weekly":
previousTime = currentTime.AddDate(0, 0, -7*4)
// monthly - last 4 months
case "monthly":
previousTime = currentTime.AddDate(0, -4, 0)
// yearly - last 4 years
case "yearly":
previousTime = currentTime.AddDate(-4, 0, 0)
}
r.Start = previousTime.Format("2006-01-02")
return r
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment