-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathisafter.go
61 lines (51 loc) · 1.94 KB
/
isafter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package validatorgo
import (
"time"
"github.com/bube054/validatorgo/sanitizer"
)
var (
isAfterOptsDefaultComparisonDate string = ""
)
// IsAfterOpts is used to configure IsAfter
type IsAfterOpts struct {
ComparisonDate string // date to be compared to. Valid layouts are from the time package e.g Layout, ANSIC, UnixDate, RubyDate, RFC822, RFC822Z, RFC850, RFC1123, RFC1123Z, Kitchen, Stamp, StampMilli, StampMicro, StampNano, DateTime, DateOnly, TimeOnly, StandardDateLayout, SlashDateLayout, DateTimeLayout, ISO8601Layout, ISO8601ZuluLayout, ISO8601WithMillisecondsLayout.
}
// A validator that checks if the string is a date that is after the specified date.
//
// IsAfterOpts is a struct that defaults to { ComparisonDate: "" }.
//
// IsAfterOpts:
//
// ComparisonDate: defaults to the current time.
//
// string layouts for str and ComparisonDate can be different layout.
//
// these are the only valid layouts from the time package
// e.g Layout, ANSIC, UnixDate, RubyDate, RFC822, RFC822Z, RFC850, RFC1123, RFC1123Z, Kitchen, Stamp, StampMilli, StampMicro, StampNano, DateTime, DateOnly, TimeOnly, StandardDateLayout, SlashDateLayout, DateTimeLayout, ISO8601Layout, ISO8601ZuluLayout, ISO8601WithMillisecondsLayout.
//
// ok := validatorgo.IsAfter("2023-09-15", &validatorgo.IsAfterOpts{ComparisonDate: "2023-01-01"})
// fmt.Println(ok) // true
// ok = validatorgo.IsAfter("2023-01-01", &validatorgo.IsAfterOpts{ComparisonDate: "2023-09-15"})
// fmt.Println(ok) // false
func IsAfter(str string, opts *IsAfterOpts) bool {
if opts == nil {
opts = setIsAfterOptsToDefault()
}
date1 := sanitizer.ToDate(str)
var date2 *time.Time
if opts.ComparisonDate == "" {
now := time.Now()
date2 = &now
} else {
date2 = sanitizer.ToDate(opts.ComparisonDate)
}
if date1 == nil || date2 == nil {
return false
}
return date1.After(*date2)
}
func setIsAfterOptsToDefault() *IsAfterOpts {
return &IsAfterOpts{
ComparisonDate: isAfterOptsDefaultComparisonDate,
}
}