File: slash_dmy.go

package info (click to toggle)
golang-github-olebedev-when 1.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 488 kB
  • sloc: makefile: 2
file content (96 lines) | stat: -rw-r--r-- 1,750 bytes parent folder | download
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package common

import (
	"regexp"
	"strconv"
	"time"

	"github.com/olebedev/when/rules"
)

/*

- DD/MM/YYYY
- 11/3/2015
- 11/3/2015
- 11/3

also with "\", gift for windows' users

https://play.golang.org/p/29LkTfe1Xr
*/

var MONTHS_DAYS = []int{
	0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
}

func getDays(year, month int) int {
	// naive leap year check
	if (year-2000)%4 == 0 && month == 2 {
		return 29
	}
	return MONTHS_DAYS[month]
}

func SlashDMY(s rules.Strategy) rules.Rule {

	return &rules.F{
		RegExp: regexp.MustCompile("(?i)(?:\\W|^)" +
			"(0{0,1}[1-9]|1[0-9]|2[0-9]|3[01])" +
			"[\\/\\\\]" +
			"(0{0,1}[1-9]|1[0-2])" +
			"(?:[\\/\\\\]" +
			"((?:1|2)[0-9]{3})\\s*)?" +
			"(?:\\W|$)"),
		Applier: func(m *rules.Match, c *rules.Context, o *rules.Options, ref time.Time) (bool, error) {
			if (c.Day != nil || c.Month != nil || c.Year != nil) && s != rules.Override {
				return false, nil
			}

			day, _ := strconv.Atoi(m.Captures[0])
			month, _ := strconv.Atoi(m.Captures[1])
			year := -1
			if m.Captures[2] != "" {
				year, _ = strconv.Atoi(m.Captures[2])
			}

			if day == 0 {
				return false, nil
			}

		WithYear:
			if year != -1 {
				if getDays(year, month) >= day {
					c.Year = &year
					c.Month = &month
					c.Day = &day
				} else {
					return false, nil
				}
				return true, nil
			}

			if int(ref.Month()) > month {
				year = ref.Year() + 1
				goto WithYear
			}

			if int(ref.Month()) == month {
				if getDays(ref.Year(), month) >= day {
					if day > ref.Day() {
						year = ref.Year()
					} else if day < ref.Day() {
						year = ref.Year() + 1
					} else {
						return false, nil
					}
					goto WithYear
				} else {
					return false, nil
				}
			}

			return true, nil
		},
	}
}