2019-05-19 21:06:07 +03:00
|
|
|
package utils
|
|
|
|
|
2020-09-06 13:15:46 +03:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
)
|
2019-05-19 21:06:07 +03:00
|
|
|
|
2020-09-12 00:24:51 +03:00
|
|
|
func StartOfToday() time.Time {
|
|
|
|
return StartOfDay(time.Now())
|
|
|
|
}
|
|
|
|
|
|
|
|
func StartOfDay(date time.Time) time.Time {
|
|
|
|
return time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())
|
2019-05-19 21:06:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func StartOfWeek() time.Time {
|
|
|
|
ref := time.Now()
|
2019-05-23 09:14:32 +03:00
|
|
|
year, week := ref.ISOWeek()
|
|
|
|
return firstDayOfISOWeek(year, week, ref.Location())
|
2019-05-19 21:06:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func StartOfMonth() time.Time {
|
|
|
|
ref := time.Now()
|
2020-08-23 14:10:58 +03:00
|
|
|
return time.Date(ref.Year(), ref.Month(), 1, 0, 0, 0, 0, ref.Location())
|
2019-05-19 21:06:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func StartOfYear() time.Time {
|
|
|
|
ref := time.Now()
|
2020-08-23 14:10:58 +03:00
|
|
|
return time.Date(ref.Year(), time.January, 1, 0, 0, 0, 0, ref.Location())
|
2019-05-19 21:06:07 +03:00
|
|
|
}
|
|
|
|
|
2020-09-12 00:24:51 +03:00
|
|
|
func SplitRangeByDays(from time.Time, to time.Time) [][]time.Time {
|
|
|
|
intervals := make([][]time.Time, 0)
|
|
|
|
|
|
|
|
for t1 := from; t1.Before(to); {
|
|
|
|
t2 := StartOfDay(t1).Add(24 * time.Hour)
|
|
|
|
if t2.After(to) {
|
|
|
|
t2 = to
|
|
|
|
}
|
|
|
|
intervals = append(intervals, []time.Time{t1, t2})
|
|
|
|
t1 = t2
|
|
|
|
}
|
|
|
|
|
|
|
|
return intervals
|
|
|
|
}
|
|
|
|
|
2020-09-06 13:15:46 +03:00
|
|
|
func FmtWakatimeDuration(d time.Duration) string {
|
|
|
|
d = d.Round(time.Minute)
|
|
|
|
h := d / time.Hour
|
|
|
|
d -= h * time.Hour
|
|
|
|
m := d / time.Minute
|
|
|
|
return fmt.Sprintf("%d hrs %d mins", h, m)
|
|
|
|
}
|
|
|
|
|
2019-05-19 21:06:07 +03:00
|
|
|
// https://stackoverflow.com/a/18632496
|
|
|
|
func firstDayOfISOWeek(year int, week int, timezone *time.Location) time.Time {
|
|
|
|
date := time.Date(year, 0, 0, 0, 0, 0, 0, timezone)
|
|
|
|
isoYear, isoWeek := date.ISOWeek()
|
|
|
|
for date.Weekday() != time.Monday { // iterate back to Monday
|
|
|
|
date = date.AddDate(0, 0, -1)
|
|
|
|
isoYear, isoWeek = date.ISOWeek()
|
|
|
|
}
|
|
|
|
for isoYear < year { // iterate forward to the first day of the first week
|
|
|
|
date = date.AddDate(0, 0, 1)
|
|
|
|
isoYear, isoWeek = date.ISOWeek()
|
|
|
|
}
|
|
|
|
for isoWeek < week { // iterate forward to the first day of the given week
|
|
|
|
date = date.AddDate(0, 0, 1)
|
|
|
|
isoYear, isoWeek = date.ISOWeek()
|
|
|
|
}
|
|
|
|
return date
|
|
|
|
}
|