-
Notifications
You must be signed in to change notification settings - Fork 9
/
datetime.go
373 lines (327 loc) · 10.5 KB
/
datetime.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package php
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// Time returns current Unix timestamp
func Time() int64 {
return time.Now().Unix()
}
// Microtime returns current Unix timestamp with microseconds
func Microtime() float64 {
return Round(float64(time.Now().UnixNano())/1000000000, 4)
}
// Strtotime parses any English textual datetime description into a Unix timestamp,
// default timezone is UTC if you do not specify one
//
// e.g. You can specify the timezone to UTC+8 by using yyyy-MM-ddThh:mm:ss+08:00
//
// Returns a timestamp on success, -1 on failure.
//
// Note that this function does not fully cover PHP's strtotime function yet
func Strtotime(str string) int64 {
t, err := DateCreate(str)
if err != nil {
return -1
}
return t.Unix()
}
// IsLeapYear checks if the given time is in a leap year
func IsLeapYear(t time.Time) bool {
t2 := time.Date(t.Year(), time.December, 31, 0, 0, 0, 0, time.UTC)
return t2.YearDay() == 366
}
// LastDateOfMonth gets the last date of the month which the given time is in
func LastDateOfMonth(t time.Time) time.Time {
t2 := FirstDateOfNextMonth(t)
return time.Unix(t2.Unix()-86400, 0)
}
// FirstDateOfMonth gets the first date of the month which the given time is in
func FirstDateOfMonth(t time.Time) time.Time {
year, month, _ := t.Date()
return time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
}
// FirstDateOfNextMonth gets the first date of next month
func FirstDateOfNextMonth(t time.Time) time.Time {
year, month, _ := t.Date()
if month == time.December {
year++
month = time.January
} else {
month++
}
return time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
}
// FirstDateOfLastMonth gets the first date of last month
func FirstDateOfLastMonth(t time.Time) time.Time {
year, month, _ := t.Date()
if month == time.January {
year--
month = time.December
} else {
month--
}
return time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
}
// recognize the character in the php date/time format string
func recognize(c string, t time.Time) string {
switch c {
// Day
case "d": // Day of the month, 2 digits with leading zeros
return fmt.Sprintf("%02d", t.Day())
case "D": // A textual representation of a day, three letters
return t.Format("Mon")
case "j": // Day of the month without leading zeros
return fmt.Sprintf("%d", t.Day())
case "l": // A full textual representation of the day of the week
return t.Weekday().String()
case "w": // Numeric representation of the day of the week
return fmt.Sprintf("%d", t.Weekday())
case "z": // The day of the year (starting from 0)
return fmt.Sprintf("%v", t.YearDay()-1)
// Week
case "W": // ISO-8601 week number of year, weeks starting on Monday
_, w := t.ISOWeek()
return fmt.Sprintf("%d", w)
// Month
case "F": // A full textual representation of a month
return t.Month().String()
case "m": // Numeric representation of a month, with leading zeros
return fmt.Sprintf("%02d", t.Month())
case "M": // A short textual representation of a month, three letters
return t.Format("Jan")
case "n": // Numeric representation of a month, without leading zeros
return fmt.Sprintf("%d", t.Month())
case "t": // Number of days in the given month
return LastDateOfMonth(t).Format("2")
// Year
case "L": // Whether it's a leap year
if IsLeapYear(t) {
return "1"
}
return "0"
case "o":
fallthrough
case "Y": // A full numeric representation of a year, 4 digits
return fmt.Sprintf("%v", t.Year())
case "y": // A two digit representation of a year
return t.Format("06")
// Time
case "a": // Lowercase Ante meridiem and Post meridiem
return t.Format("pm")
case "A": // Uppercase Ante meridiem and Post meridiem
return strings.ToUpper(t.Format("pm"))
case "g": // 12-hour format of an hour without leading zeros
return t.Format("3")
case "G": // 24-hour format of an hour without leading zeros
return fmt.Sprintf("%d", t.Hour())
case "h": // 12-hour format of an hour with leading zeros
return t.Format("03")
case "H": // 24-hour format of an hour with leading zeros
return fmt.Sprintf("%02d", t.Hour())
case "i": // Minutes with leading zeros
return fmt.Sprintf("%02d", t.Minute())
case "s": // Seconds, with leading zeros
return fmt.Sprintf("%02d", t.Second())
case "e": // Timezone identifier
fallthrough
case "T": // Timezone abbreviation
return t.Format("MST")
case "O": // Difference to Greenwich time (GMT) in hours
return t.Format("-0700")
case "P": // Difference to Greenwich time (GMT) with colon between hours and minutes
return t.Format("-07:00")
case "U": // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
return fmt.Sprintf("%v", t.Unix())
default:
return c
}
}
// parse returns a textual representation of the time value formatted
// according to the given php date/time format string
func parse(format string, t time.Time) string {
result := ""
for _, s := range format {
result += recognize(string(s), t)
}
return result
}
// format is a wrapper of parse
func format(f string, t time.Time) string {
pattern, err := getPattern(f)
if err != nil {
return parse(f, t)
}
return t.Format(pattern.layout)
}
// Date returns a string formatted according to the given format string using the given integer timestamp
//
// Note that the timezone is set to UTC
func Date(f string, timestamp int64) string {
return format(f, time.Unix(timestamp, 0).UTC())
}
// Today returns a string formatted according to the given format string using current timestamp
//
// Note that the timezone is using local timezone
func Today(f string) string {
return format(f, time.Now())
}
// LocalDate returns a string formatted according to the given format string using the given integer timestamp
//
// Note that the timezone is using local timezone
func LocalDate(f string, timestamp int64) string {
return format(f, time.Unix(timestamp, 0))
}
// Checkdate validates a Gregorian date
func Checkdate(month, day, year int) bool {
if month < 1 || month > 12 || day < 1 || day > 31 || year <= 0 {
return false
}
_, err := time.Parse("2006-1-2", fmt.Sprintf("%04d-%d-%d", year, month, day))
return err == nil
}
// DateCreateFromFormat parses a date/time string according to a specified format
func DateCreateFromFormat(f string, t string) (time.Time, error) {
return time.Parse(convertLayout(f), t)
}
// DateCreate parses a date/time string and return a time.Time.
// Supported Date and Time Formats: https://www.php.net/manual/en/datetime.formats.php
func DateCreate(str string) (time.Time, error) {
if strings.ToLower(str) == "now" {
return time.Now(), nil
}
duration, err := DateIntervalCreateFromDateString(str)
if err == nil {
return time.Now().Add(duration), nil
}
for _, p := range _defaultPatterns {
reg := regexp.MustCompile(p.regexp)
if reg.MatchString(str) {
t, err := time.Parse(p.layout, str)
if err == nil {
return t, nil
}
}
}
return time.Time{}, errors.New("Unsupported date/time string: " + str)
}
// DateDateSet sets the date by year, month and day
func DateDateSet(year, month, day int) (time.Time, error) {
return time.Parse("2006-1-2", fmt.Sprintf("%04d-%d-%d", year, month, day))
}
// DateDefaultTimezoneGet gets the default timezone
func DateDefaultTimezoneGet() string {
tz, _ := time.Now().Local().Zone()
return tz
}
// DateDefaultTimezoneSet sets the default timezone
func DateDefaultTimezoneSet(tz string) error {
loc, err := time.LoadLocation(tz)
if err != nil {
return err
}
time.Local = loc
return nil
}
// DateTimezoneGet gets the timezone of the given time
func DateTimezoneGet(t time.Time) string {
tz, _ := t.Zone()
return tz
}
// DateTimezoneSet returns a copy of t with the given timezone
func DateTimezoneSet(t time.Time, tz string) (time.Time, error) {
loc, err := time.LoadLocation(tz)
if err != nil {
return t, err
}
return t.In(loc), nil
}
// DateDiff returns the difference between two times (t2 - t1)
func DateDiff(t1 time.Time, t2 time.Time) time.Duration {
return t2.Sub(t1)
}
// DateFormat returns a string formatted according to the given format string using the given time
func DateFormat(t time.Time, f string) string {
return format(f, t)
}
// DateIntervalCreateFromDateString returns a time.Duration from the given string
func DateIntervalCreateFromDateString(str string) (time.Duration, error) {
reg := regexp.MustCompile(`((\+|\-)?\s*(\d*)\s*(day|month|year|week|hour|minute|second)s?\s*)+?`)
matches := reg.FindAllStringSubmatch(str, -1)
if matches != nil {
var duration int64
for _, match := range matches {
var diff, num int64
if match[3] == "" {
num = 1
} else {
num, _ = strconv.ParseInt(match[3], 10, 64)
}
switch match[4] {
case "day":
diff = num * 86400
case "month":
diff = num * 86400 * 30
case "year":
diff = num * 86400 * 365
case "week":
diff = num * 86400 * 7
case "hour":
diff = num * 3600
case "minute":
diff = num * 60
case "second":
diff = num
}
if match[2] == "-" {
diff = -diff
}
duration += diff
}
return time.Duration(duration) * time.Second, nil
}
return 0, errors.New("unsupported string format")
}
// DateISODateSet sets a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates
func DateISODateSet(year, week, day int) (time.Time, error) {
firstDateOfYear, err := time.Parse("2006-1-2", fmt.Sprintf("%04d-%d-%d", year, 1, 1))
if err != nil {
return time.Time{}, err
}
offset := time.Duration(1-firstDateOfYear.Weekday()) * 24 * time.Hour
firstDateOfFirstWeek := firstDateOfYear.Add(offset)
return firstDateOfFirstWeek.Add(time.Duration(((week-1)*7+day-1)*24) * time.Hour), nil
}
// DateModify alter the time by the given format
func DateModify(t time.Time, modify string) (time.Time, error) {
duration, err := DateIntervalCreateFromDateString(modify)
if err != nil {
return t, err
}
return t.Add(duration), nil
}
// DateOffsetGet returns the timezone offset
func DateOffsetGet(t time.Time) int {
_, offset := t.Zone()
return offset
}
// DateAdd adds an amount of days, months, years, hours, minutes and seconds to the time t
func DateAdd(t time.Time, d time.Duration) time.Time {
return t.Add(d)
}
// DateSub subtracts an amount of days, months, years, hours, minutes and seconds from the time t
func DateSub(t time.Time, d time.Duration) time.Time {
return t.Add(-d)
}
// DateTimestampGet gets the Unix timestamp
func DateTimestampGet(t time.Time) int64 {
return t.Unix()
}
// DateTimestampSet sets the date and time based on an Unix timestamp
func DateTimestampSet(timestamp int64) time.Time {
return time.Unix(timestamp, 0)
}