0

I've written a todo handler API and want to add a condition to check if inputted DueDate by user is less than tomorrow date,how should I write it instead of ???? in following code?

type Todo struct {
    gorm.Model

    Title string `json:"title,omitempty"`
    Description string `json:"description,omitempty"`
    DueDate time.Time `json:"duedate,omitempty"`

    UserId uint   `json:"user_id"` //The user that this todo belongs to
}

func  ValidateTodo(todo *Todo) (map[string]interface{}, bool) {

    if todo.Title == "" {
        return u.Message(false, "Todo title should be on the payload"), false
    }

    if len(todo.Title)>30 {
        return u.Message(false, "Todo title should be less than 30 characters"), false
    }

    if todo.Description == "" {
        return u.Message(false, "Todo description should be on the payload"), false
    }

    if todo.DueDate<time.Now(){
       ?????
    }
    return u.Message(true, "success"), true

}
Siavoosh
  • 181
  • 1
  • 1
  • 5

1 Answers1

2

You an do this with a combination of time.AddDate() and time.Before()

dueDate := time.Now()
tomorrow := time.Now().AddDate(0, 0, 1)

if tomorrow.Before(dueDate) {
    fmt.Println("Tomorrow is before your due date")
}

Edit: Volker's comment raises a good point actually. time.After() would probably make more logical sense to use for readability. So you could do the following;

dueDate := time.Now()
tomorrow := time.Now().AddDate(0, 0, 1)

if dueDate.After(tomorrow) {
    fmt.Println("Due date is after tomorrow")
}

Edit2: Update to zero out time based on the desire to have tomorrow's time at 00:00:00

tomorrow := time.Now().AddDate(0, 0, 1)
tomorrowZeroTime, err := time.Parse("Mon Jan 2 2006", tomorrow.Format("Mon Jan 2 2006"))
if err != nil {
    // Handle Error
}

dueDate := time.Now()
if dueDate.After(tomorrowZeroTime) {
    fmt.Println("Due date is after tomorrow")
} 
Mikey
  • 2,606
  • 1
  • 12
  • 20
  • thanks a lot, its a good idea, but it will add 24hours to tomorrow according to current time, but I need to consider the date only not about the hour of the day. – Siavoosh Mar 03 '20 at 14:59
  • `AddDate()` does *NOT* add 24 hours per day ([source](https://golang.org/src/time/time.go?s=29842:29901#L945)). It creates a brand new `time.Time` adding the specific number of year/month/days to the source time's date. Doing time.Duration calculations after a `AddDate(0,0,1)` will not always yield a 24 hour duration e.g. if the two dates span a DST shift. – colm.anseo Mar 03 '20 at 15:30
  • 1
    Basically you want to zero out the time before you do your check from what I gather from that @Siasalar updated the answer with one way to do that. Essentially you format and re-parse. Unsure if there's a better way to do it personally. – Mikey Mar 03 '20 at 15:46
  • thanks a lot guys, it helped me a lot and working properly. – Siavoosh Mar 04 '20 at 09:07