首页 > 解决方案 > 如何检查rest api中的截止日期是否大于明天

问题描述

我已经编写了一个待办事项处理程序 API,并且想添加一个条件来检查用户输入的 DueDate 是否小于明天的日期,我应该如何编写它而不是 ???? 在下面的代码中?

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

}

标签: restgo

解决方案


您可以结合使用time.AddDate()time.Before()

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

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

编辑:沃尔克的评论实际上提出了一个很好的观点。time.After()用于可读性可能更合乎逻辑。因此,您可以执行以下操作;

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

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

Edit2:根据希望明天的时间在 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")
} 

推荐阅读