计算开始日期与到期日期之间的天数差异,并计算到到期日期为止的剩余天数

There are startDate and dueDate on my model. What I want is to attach daysToStart, daysLeft and duration fields on model, according to its startDate and dueDate values.

  • daysLeft should be difference in days from now till startDate
  • duration is number of days between start and due date
  • daysToStart is difference between now and startDate

startDate and dueDate are stored in db as time.Time. All calculations should be normalized to UTC time.

EDIT: startDate: "2019-07-09T00:00:00Z" dueDate: "2019-07-10T00:00:00Z"

type Objective struct {
  // fields
}

// attach daysLeft, duration and daysToStart

func (r *Objective) calculateDuration() {
    r.Duration = int(math.Round(r.DueDate.Sub(r.StartDate).Hours() / 24))
}

func (r *Objective) calculateDaysLeft() {
    r.DaysLeft = int(math.Round(r.DueDate.Sub(time.Now().UTC()).Hours()/24)) + 1
}

func (r *Objective) calculateDaysToStart() {
    r.DaysToStart = int(math.Round(r.StartDate.Sub(time.Now().UTC()).Hours()/24)) + 1
}

For provided example, it returns incorrect values, for example it returns dasToStart = 1 although startDate is today, so it should be zero.