prime8dev

prime8dev
git clone https://git.prime8.dev/prime8dev.git
Log | Files | Refs | README | LICENSE

period.go (1834B)


      1 package utils
      2 
      3 import (
      4 	"fmt"
      5 	"strings"
      6 	"time"
      7 )
      8 
      9 var monthNames = []string{
     10 	"january",
     11 	"february",
     12 	"march",
     13 	"april",
     14 	"may",
     15 	"june",
     16 	"july",
     17 	"august",
     18 	"september",
     19 	"october",
     20 	"november",
     21 	"december",
     22 }
     23 
     24 func FormatMonthYear(t time.Time) string {
     25 	month := int(t.Month()) - 1
     26 	if month < 0 || month >= len(monthNames) {
     27 		return strings.ToLower(t.Format("Jan 2006"))
     28 	}
     29 
     30 	return fmt.Sprintf("%s %s", monthNames[month], t.Format("2006"))
     31 }
     32 
     33 func FormatEndDate(endDate *time.Time, current bool) string {
     34 	if current || endDate == nil {
     35 		return "present"
     36 	}
     37 
     38 	return FormatMonthYear(*endDate)
     39 }
     40 
     41 func MonthsDuration(startDate time.Time, endDate *time.Time, current bool) int {
     42 	end := time.Now()
     43 	if !current && endDate != nil {
     44 		end = *endDate
     45 	}
     46 
     47 	months := (end.Year()-startDate.Year())*12 + int(end.Month()-startDate.Month()) + 1
     48 	if months < 1 {
     49 		return 1
     50 	}
     51 
     52 	return months
     53 }
     54 
     55 func MonthWord(months int) string {
     56 	if months == 1 {
     57 		return "month"
     58 	}
     59 
     60 	return "months"
     61 }
     62 
     63 func FormatDuration(startDate time.Time, endDate *time.Time, current bool) string {
     64 	months := MonthsDuration(startDate, endDate, current)
     65 	years := months / 12
     66 	remainingMonths := months % 12
     67 
     68 	if years == 0 {
     69 		return fmt.Sprintf("%d %s", months, MonthWord(months))
     70 	}
     71 
     72 	if remainingMonths == 0 {
     73 		return fmt.Sprintf("%d %s", years, yearWord(years))
     74 	}
     75 
     76 	return fmt.Sprintf("%d %s %d %s", years, yearWord(years), remainingMonths, MonthWord(remainingMonths))
     77 }
     78 
     79 func DurationHasYear(startDate time.Time, endDate *time.Time, current bool) bool {
     80 	return MonthsDuration(startDate, endDate, current) >= 12
     81 }
     82 
     83 func yearWord(years int) string {
     84 	if years == 1 {
     85 		return "year"
     86 	}
     87 
     88 	return "years"
     89 }
     90 
     91 func TimelineYear(endDate *time.Time, current bool) string {
     92 	if current || endDate == nil {
     93 		return "now"
     94 	}
     95 
     96 	return endDate.Format("2006")
     97 }