2019-07-17 12:42:00 +01:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
// Package date contains various date-related utilities
|
|
|
|
package date
|
|
|
|
|
|
|
|
import "time"
|
|
|
|
|
2020-07-16 15:18:02 +01:00
|
|
|
// MonthBoundary extract month from the provided date and returns its edges.
|
2019-08-08 14:47:04 +01:00
|
|
|
func MonthBoundary(t time.Time) (time.Time, time.Time) {
|
|
|
|
startDate := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
|
|
|
|
endDate := time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, -1, t.Location())
|
|
|
|
return startDate, endDate
|
2019-07-17 12:42:00 +01:00
|
|
|
}
|
|
|
|
|
2020-07-16 15:18:02 +01:00
|
|
|
// DayBoundary returns start and end of the provided day.
|
2019-07-17 12:42:00 +01:00
|
|
|
func DayBoundary(t time.Time) (time.Time, time.Time) {
|
2019-08-08 14:47:04 +01:00
|
|
|
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()),
|
|
|
|
time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, -1, t.Location())
|
2019-07-17 12:42:00 +01:00
|
|
|
}
|
2020-03-17 10:06:20 +00:00
|
|
|
|
|
|
|
// PeriodToTime returns time.Time period in format YYYY-MM from string.
|
|
|
|
func PeriodToTime(period string) (_ time.Time, err error) {
|
|
|
|
layout := "2006-01"
|
|
|
|
shortPeriod := period[0:7]
|
|
|
|
result, err := time.Parse(layout, shortPeriod)
|
|
|
|
if err != nil {
|
|
|
|
return time.Time{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|
2020-05-10 12:23:13 +01:00
|
|
|
|
|
|
|
// MonthsCountSince calculates the months between now and the createdAtTime time.Time value passed.
|
|
|
|
func MonthsCountSince(from time.Time) int {
|
2020-06-30 22:26:31 +01:00
|
|
|
return MonthsBetweenDates(from, time.Now())
|
2020-05-10 12:23:13 +01:00
|
|
|
}
|
|
|
|
|
2020-07-16 15:18:02 +01:00
|
|
|
// MonthsBetweenDates calculates amount of months between two dates.
|
2020-05-10 12:23:13 +01:00
|
|
|
func MonthsBetweenDates(from time.Time, to time.Time) int {
|
2020-06-30 22:26:31 +01:00
|
|
|
// we need UTC here before its the only sensible way to say what day it is
|
|
|
|
y1, M1, _ := from.UTC().Date()
|
|
|
|
y2, M2, _ := to.UTC().Date()
|
2020-05-10 12:23:13 +01:00
|
|
|
|
2020-06-30 22:26:31 +01:00
|
|
|
months := ((y2 - y1) * 12) + int(M2) - int(M1)
|
|
|
|
//note that according to the tests, we ignore days of the month
|
2020-05-10 12:23:13 +01:00
|
|
|
return months
|
|
|
|
}
|
2020-06-11 19:31:45 +01:00
|
|
|
|
2020-07-16 15:18:02 +01:00
|
|
|
// TruncateToHourInNano returns the time truncated to the hour in nanoseconds.
|
2020-06-11 19:31:45 +01:00
|
|
|
func TruncateToHourInNano(t time.Time) int64 {
|
|
|
|
return t.Truncate(1 * time.Hour).UnixNano()
|
|
|
|
}
|