-
Notifications
You must be signed in to change notification settings - Fork 0
/
mes.go
346 lines (298 loc) · 7.3 KB
/
mes.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package fecha
import (
"database/sql/driver"
"fmt"
"strconv"
"strings"
"time"
)
// AñoMinimo determina que si se ingresa una fecha con año menor,
// el período será considerado inválido.
const AñoMinimo = 1900
// AñoMaximo determina que si se ingresa una fecha con año posterior,
// el período será considerado inválido.
const AñoMaximo = 2200
// SeparadorMes es el caracter utilizado para separar el mes de año
// al mostrarlo como string
const SeparadorMes = "/"
// MesPrimero true: 03/2020. Si es false se muestra 2020/03
const MesPrimero = true
// Mes es una estructura para representar un mes calendario de un año particular.Mes
// Reduce la ambiguedad ya que no es necesario ingresar un día.
//
// Se usaron variables locales para evitar tener una fecha en un estado
// inválido.
//
// En JSON se marshaliza con el formato "2020-08"
// En la base de datos se persiste como un DATE
type Mes struct {
año int
mes int
}
var NilMes = Mes{}
func NewMesMust(año, mes int) Mes {
m := Mes{año, mes}
if m.mes < 1 || m.mes > 12 {
panic(fmt.Errorf("invalid month '%v' (must be between 1 and 12)", m.mes))
}
if m.año < AñoMinimo || m.año > AñoMaximo {
panic(fmt.Errorf("year '%v' out of range (must be between %v and %v)", m.año, AñoMinimo, AñoMaximo))
}
return m
}
func NewMes(año, mes int) (Mes, error) {
m := Mes{año, mes}
if m.mes < 1 || m.mes > 12 {
return m, fmt.Errorf("invalid month '%v' (must be between 1 and 12)", m.mes)
}
if m.año < AñoMinimo || m.año > AñoMaximo {
return m, fmt.Errorf("year '%v' out of range (must be between %v and %v)", m.año, AñoMinimo, AñoMaximo)
}
return m, nil
}
func NewMesFromJSON(str string) (out Mes, err error) {
if len(str) != 7 {
return out, fmt.Errorf("incorrect format: expected YYYY-MM; got: %v", str)
}
partes := strings.Split(str, "-")
if len(partes) != 2 {
return out, fmt.Errorf("incorrect format: expected YYYY-MM; got: %v", str)
}
año, err := strconv.Atoi(partes[0])
if err != nil {
return out, fmt.Errorf("invalid year '%v': %w", str, err)
}
mes, err := strconv.Atoi(partes[1])
if err != nil {
return out, fmt.Errorf("invalid month '%v': %w", str, err)
}
return NewMes(año, mes)
}
// MesDelAño devuelve el número de mes.
func (m Mes) MesDelAño() int {
return m.mes
}
// Año devuelve el número del año.
func (m Mes) Año() int {
return m.año
}
func (m Mes) Anterior(f2 Mes) bool {
if m.año > f2.año { // 2030 > 2021
return false
}
if m.año < f2.año { // 2030 > 2021
return true
}
// Son años distintos, define mes
return m.mes < f2.mes
}
func (m Mes) AnteriorOIgual(f2 Mes) bool {
if m == f2 {
return true
}
return m.Anterior(f2)
}
func (m Mes) Posterior(f2 Mes) bool {
if m.año > f2.año {
return true
}
if m.año < f2.año {
return false
}
return m.mes > f2.mes
}
func (m Mes) PosteriorOIgual(f2 Mes) bool {
if m == f2 {
return true
}
return m.Posterior(f2)
}
func (m Mes) String() (out string) {
if !m.Valid() {
return "mes inválido"
}
año := ""
mes := ""
switch {
case m.año >= 1000:
año = fmt.Sprint(m.año)
case m.año >= 100:
año = fmt.Sprint("0", m.año)
case m.año >= 10:
año = fmt.Sprint("00", m.año)
case m.año >= 1:
año = fmt.Sprint("000", m.año)
}
switch {
case m.mes < 10:
mes = fmt.Sprint("0", m.mes)
default:
mes = fmt.Sprint(m.mes)
}
switch MesPrimero {
case true:
return fmt.Sprintf("%v%v%v", mes, SeparadorMes, año)
case false:
return fmt.Sprintf("%v%v%v", año, SeparadorMes, mes)
}
return
}
// Valid devuelve true si la fecha es válida
func (m Mes) Valid() bool {
// fmt.Println(m)
if m.mes < 1 || m.mes > 12 {
return false
}
if m.año < AñoMinimo || m.año > AñoMaximo {
return false
}
return true
}
// Zero devuelve true si el día y el año son cero
func (m Mes) Zero() bool {
if m.año == 0 && m.mes == 0 {
return true
}
return false
}
// SumarMeses devuelve una nueva fecha con los meses agregados.
// Si se quiere restar, ingresar meses en negativo.
// Se supone que se está trabajando con un Mes válido no cero.
func (m Mes) SumarMeses(meses int) (out Mes) {
out.año = m.año
out.mes = m.mes + meses
switch {
case meses > 0:
for {
if out.mes <= 12 {
return out
}
out.mes -= 12
out.año++
}
case meses < 0:
for {
if out.mes > 0 {
return out
}
out.mes += 12
out.año--
}
}
return m
}
// PrimerDia devuelve la fecha considerando el primer día del período.
func (m Mes) PrimerDia() Fecha {
return NewFechaFromInts(m.año, m.mes, 1)
}
// UltimoDia devuelve la fecha considerando el último día del período.
func (m Mes) UltimoDia() Fecha {
return NewFechaFromInts(m.año, m.mes, ultimoDia(m.mes, m.año))
}
// JSONString devuelve la representación que se utiliza en JSON.
// Si es cero devuelve null
// Si no es válida devuelve "N/D"
func (m Mes) JSONString() string {
if !m.Valid() {
return "null"
}
if !m.Valid() {
return "N/D"
}
año := ""
mes := ""
switch {
case m.año >= 1000:
año = fmt.Sprint(m.año)
case m.año >= 100:
año = fmt.Sprint("0", m.año)
case m.año >= 10:
año = fmt.Sprint("00", m.año)
case m.año >= 1:
año = fmt.Sprint("000", m.año)
}
switch {
case m.mes < 10:
mes = fmt.Sprint("0", m.mes)
default:
mes = fmt.Sprint(m.mes)
}
return fmt.Sprintf("%v-%v", año, mes)
}
// Value satisface la interface de package sql.
// En la base de datos la guarda como el tipo DATE.
// Si se intenta persistir una fecha Zero() => La guarda como null.
// Si se intenta persistir una fecha !Valid() => devuelve error.
func (m Mes) Value() (driver.Value, error) {
if m.Zero() {
return nil, nil
}
if !m.Valid() {
return m, fmt.Errorf("invalid month '%v' (must be between 1 and 12)", m.mes)
}
return m.PrimerDia().Time(), nil
}
// Scan satisface la interface de package sql.
// Si el valor que estaba persistido es menor al mínimo o mayor al máximo,
// no va a dar a error. Queda a criterio del usuario analizarla con
// el método Valid().
// Si el va
func (m *Mes) Scan(value interface{}) error {
if value == nil {
*m = Mes{}
}
enTime, ok := value.(time.Time)
if !ok {
return fmt.Errorf("expected value type: time.Time, got: %T", value)
}
*m = NewFechaFromTime(enTime).PeriodoMes()
return nil
}
// MarshalJSON es para tomar una una struct a un string JSON.
func (m Mes) MarshalJSON() (by []byte, err error) {
if m.Zero() {
by = []byte("null")
return by, nil
}
if !m.Valid() {
return by, fmt.Errorf("no se puede marshalizar la fecha %v, (no es válida)", m)
}
by = []byte(`"` + m.JSONString() + `"`)
return by, nil
}
// UnmarshalJSON es para parsear el string a una struct Mes.
// Si llega una cadena null o vacía, se crea una struct con valor cero.
func (m *Mes) UnmarshalJSON(input []byte) (err error) {
texto := string(input)
if texto == "null" || texto == `""` {
*m = Mes{}
return nil
}
// Quito las comillas
texto = strings.Replace(texto, `"`, "", -1)
// Si la fecha viene en formato Date de Javascript(), tomo la primera parte nomás
// 2020-02-04T03:00:00.000Z
if len(texto) == 24 {
texto = texto[:7]
}
if m == nil {
m = new(Mes)
}
*m, err = NewMesFromJSON(texto)
return
}
func ultimoDia(mes int, año int) (out int) {
out = 31
switch mes {
case 2, 4, 6, 9, 11:
out = 30
}
if mes == 2 {
if año%4 == 0 && año%100 != 0 || año%400 == 0 {
return 29
} else {
return 28
}
}
return
}