File: dot_date_time.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 (61 lines) | stat: -rw-r--r-- 1,526 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
package ru

import (
	"regexp"
	"strconv"
	"time"

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

// https://go.dev/play/p/vRzLhHHupUJ

func DotDateTime(s rules.Strategy) rules.Rule {
	return &rules.F{
		RegExp: regexp.MustCompile(`(?i)(?:^|\b)(\d{2})\.(\d{2})\.(\d{4})(?:\s+(\d{2}):(\d{2}))?(?:\b|$)`),
		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 || c.Hour != nil || c.Minute != nil) && s != rules.Override {
				return false, nil
			}

			day, err := strconv.Atoi(m.Captures[0])
			if err != nil {
				return false, errors.Wrap(err, "dot date time rule: day")
			}

			month, err := strconv.Atoi(m.Captures[1])
			if err != nil {
				return false, errors.Wrap(err, "dot date time rule: month")
			}

			year, err := strconv.Atoi(m.Captures[2])
			if err != nil {
				return false, errors.Wrap(err, "dot date time rule: year")
			}

			hour, minute := 0, 0
			if m.Captures[3] != "" && m.Captures[4] != "" {
				hour, err = strconv.Atoi(m.Captures[3])
				if err != nil {
					return false, errors.Wrap(err, "dot date time rule: hour")
				}
				minute, err = strconv.Atoi(m.Captures[4])
				if err != nil {
					return false, errors.Wrap(err, "dot date time rule: minute")
				}
			}

			if day > 0 && day <= 31 && month > 0 && month <= 12 {
				c.Day = &day
				c.Month = &month
				c.Year = &year
				c.Hour = &hour
				c.Minute = &minute
				return true, nil
			}

			return false, nil
		},
	}
}