73 lines
1.6 KiB
Go
73 lines
1.6 KiB
Go
package datetime
|
|
|
|
import (
|
|
"math"
|
|
"time"
|
|
)
|
|
|
|
// DiffInYears retourne (t1 - t2) exprimé en années.
|
|
func DiffInYears(t1, t2 time.Time) int64 {
|
|
y1, m1, d1 := t1.Date()
|
|
y2, m2, d2 := t2.Date()
|
|
|
|
dy, dm, dd := y1-y2, m1-m2, d1-d2
|
|
if dm < 0 || (dm == 0 && dd < 0) {
|
|
dy--
|
|
}
|
|
if dy < 0 && (dd != 0 || dm != 0) {
|
|
dy++
|
|
}
|
|
|
|
return int64(dy)
|
|
}
|
|
|
|
// DiffInMonths retourne (t1 - t2) exprimé en mois.
|
|
func DiffInMonths(t1, t2 time.Time) int64 {
|
|
y1, m1, d1 := t1.Date()
|
|
y2, m2, d2 := t2.Date()
|
|
|
|
dy, dm, dd := y1-y2, m1-m2, d1-d2
|
|
if dd < 0 {
|
|
dm--
|
|
}
|
|
if dy == 0 && dm == 0 {
|
|
return int64(dm)
|
|
}
|
|
if dy == 0 && dm != 0 && dd != 0 {
|
|
dh := abs(DiffInHours(t1, t2))
|
|
if int(dh) < DaysInMonth(t1)*HoursPerDay {
|
|
return int64(0)
|
|
}
|
|
return int64(dm)
|
|
}
|
|
|
|
return int64(dy*MonthsPerYear + int(dm))
|
|
}
|
|
|
|
// DiffInWeeks retourne (t1 - t2) exprimé en semaines.
|
|
func DiffInWeeks(t1, t2 time.Time) int64 {
|
|
return int64(math.Floor(float64(DiffInSeconds(t1, t2)) / float64(SecondsPerWeek)))
|
|
}
|
|
|
|
// DiffInDays retourne (t1 - t2) exprimé en jours.
|
|
func DiffInDays(t1, t2 time.Time) int64 {
|
|
return int64(math.Floor(float64(DiffInSeconds(t1, t2)) / float64(SecondsPerDay)))
|
|
}
|
|
|
|
// DiffInHours retourne (t1 - t2) exprimé en heures.
|
|
func DiffInHours(t1, t2 time.Time) int64 {
|
|
|
|
return DiffInSeconds(t1, t2) / SecondsPerHour
|
|
}
|
|
|
|
// DiffInMinutes retourne (t1 - t2) exprimé en minutes.
|
|
func DiffInMinutes(t1, t2 time.Time) int64 {
|
|
|
|
return DiffInSeconds(t1, t2) / SecondsPerMinute
|
|
}
|
|
|
|
// DiffInSeconds retourne (t1 - t2) exprimé en secondes.
|
|
func DiffInSeconds(t1, t2 time.Time) int64 {
|
|
return t1.Unix() - t2.Unix()
|
|
}
|