v
Зеркало из https://github.com/vlang/v
1// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4module time
5
6import strconv
7
8// parse_rfc3339 returns the time from a date string in RFC 3339 datetime format.
9// See also https://ijmacd.github.io/rfc3339-iso8601/ for a visual reference of
10// the differences between ISO-8601 and RFC 3339.
11pub fn parse_rfc3339(s string) !Time {
12if s == '' {
13return error_invalid_time(0, 'datetime string is empty')
14}
15// Normalize the input before parsing. Good since iso8601 doesn't permit lower case `t` and `z`.
16sn := s.replace_each(['t', 'T', 'z', 'Z'])
17mut t := parse_iso8601(sn) or { Time{} }
18// If parse_iso8601 DID NOT result in default values (i.e. date was parsed correctly)
19if t != Time{} {
20return t
21}
22
23t_i := sn.index('T') or { -1 }
24parts := if t_i != -1 { [sn[..t_i], sn[t_i + 1..]] } else { sn.split(' ') }
25
26// Check if sn is date only
27if !parts[0].contains_any(' Z') && parts[0].contains('-') {
28year, month, day := parse_iso8601_date(sn)!
29t = new(Time{
30year: year
31month: month
32day: day
33})
34return t
35}
36// Check if sn is time only
37if !parts[0].contains('-') && parts[0].contains(':') {
38mut hour_, mut minute_, mut second_, mut microsecond_, mut nanosecond_, mut unix_offset, mut is_local_time := 0, 0, 0, 0, 0, i64(0), true
39hour_, minute_, second_, microsecond_, nanosecond_, unix_offset, is_local_time = parse_iso8601_time(parts[0])!
40t = new(Time{
41hour: hour_
42minute: minute_
43second: second_
44nanosecond: nanosecond_
45})
46if is_local_time {
47return t // Time is already local time
48}
49mut unix_time := t.unix
50if unix_offset < 0 {
51unix_time -= (-unix_offset)
52} else if unix_offset > 0 {
53unix_time += unix_offset
54}
55t = unix_nanosecond(i64(unix_time), t.nanosecond)
56return t
57}
58
59return error_invalid_time(9, 'malformed date')
60}
61
62// parse returns the time from a date string in "YYYY-MM-DD HH:mm:ss" format.
63pub fn parse(s string) !Time {
64if s == '' {
65return error_invalid_time(0, 'datetime string is empty')
66}
67pos := s.index(' ') or {
68return error_invalid_time(1, 'string has no space between date and time')
69}
70symd := s[..pos]
71ymd := symd.split('-')
72if ymd.len != 3 {
73return error_invalid_time(2, 'date must be in the form of y-m-d')
74}
75shms := s[pos..]
76hms := shms.split(':')
77if hms.len != 3 {
78return error_invalid_time(9, 'time must be in the form of H:i:s')
79}
80hour_ := hms[0][1..]
81minute_ := hms[1]
82second_ := hms[2]
83
84iyear := strconv.atoi(ymd[0]) or {
85return error_invalid_time(0, 'invalid year format: ${ymd[0]}')
86}
87imonth := strconv.atoi(ymd[1]) or {
88return error_invalid_time(0, 'invalid month format: ${ymd[1]}')
89}
90iday := strconv.atoi(ymd[2]) or {
91return error_invalid_time(0, 'invalid day format: ${ymd[2]}')
92}
93ihour := strconv.atoi(hour_) or {
94return error_invalid_time(0, 'invalid hour format: ${hour_}')
95}
96iminute := strconv.atoi(minute_) or {
97return error_invalid_time(0, 'invalid minute format: ${minute_}')
98}
99isecond := strconv.atoi(second_) or {
100return error_invalid_time(0, 'invalid second format: ${second_}')
101}
102
103// eprintln('>> iyear: $iyear | imonth: $imonth | iday: $iday | ihour: $ihour | iminute: $iminute | isecond: $isecond')
104if iyear > 9999 || iyear < -9999 {
105return error_invalid_time(3, 'year must be between -10000 and 10000')
106}
107if imonth > 12 || imonth < 1 {
108return error_invalid_time(4, 'month must be between 1 and 12')
109}
110if iday > 31 || iday < 1 {
111return error_invalid_time(5, 'day must be between 1 and 31')
112}
113if ihour > 23 || ihour < 0 {
114return error_invalid_time(6, 'hours must be between 0 and 24')
115}
116if iminute > 59 || iminute < 0 {
117return error_invalid_time(7, 'minutes must be between 0 and 60')
118}
119if isecond > 59 || isecond < 0 {
120return error_invalid_time(8, 'seconds must be between 0 and 60')
121}
122res := new(Time{
123year: iyear
124month: imonth
125day: iday
126hour: ihour
127minute: iminute
128second: isecond
129})
130return res
131}
132
133// parse_format parses the string `s`, as a custom `format`, containing the following specifiers:
134//
135// |Category| Format | Description |
136// |:----- | :----- | :---------- |
137// |Year | YYYY | 4 digit year, 0000..9999 |
138// | | YY | 2 digit year, 00..99 |
139// |Month | M | month, 1..12 |
140// | | MM | month, 2 digits, 01..12 |
141// | | MMM | month, three letters, Jan..Dec |
142// | | MMMM | name of month |
143// |Day | D | day of the month, 1..31 |
144// | | DD | day of the month, 01..31 |
145// | | d | day of week, 0..6 |
146// | | c | day of week, 1..7 |
147// | | dd | day of week, Su..Sa |
148// | | ddd | day of week, Sun..Sat |
149// | | dddd | day of week, Sunday..Saturday |
150// |Hour | H | hour, 0..23 |
151// | | HH | hour, 00..23 |
152// | | h | hour, 0..23 |
153// | | hh | hour, 0..23 |
154// | | k | hour, 0..23 |
155// | | kk | hour, 0..23 |
156// |Minute | m | minute, 0..59 |
157// | | mm | minute, 0..59 |
158// |Second | s | second, 0..59 |
159// | | ss | second, 0..59 |
160pub fn parse_format(s string, format string) !Time {
161if s == '' {
162return error_invalid_time(0, 'datetime string is empty')
163}
164mut p := new_date_time_parser(s, format)
165return p.parse()
166}
167
168// parse_iso8601 parses the ISO 8601 time format yyyy-MM-ddTHH:mm:ss.dddddd+dd:dd as local time.
169// The fraction part is difference in milli seconds, and the last part is offset from UTC time.
170// Both can be +/- HH:mm .
171// See https://en.wikipedia.org/wiki/ISO_8601 .
172// Remarks: not all of ISO 8601 is supported; checks and support for leapseconds should be added.
173pub fn parse_iso8601(s string) !Time {
174if s == '' {
175return error_invalid_time(0, 'datetime string is empty')
176}
177t_i := s.index('T') or { -1 }
178parts := if t_i != -1 { [s[..t_i], s[t_i + 1..]] } else { s.split(' ') }
179if !(parts.len == 1 || parts.len == 2) {
180return error_invalid_time(12, 'malformed date')
181}
182year, month, day := parse_iso8601_date(parts[0])!
183mut hour_, mut minute_, mut second_, mut microsecond_, mut nanosecond_, mut unix_offset, mut is_local_time := 0, 0, 0, 0, 0, i64(0), true
184if parts.len == 2 {
185hour_, minute_, second_, microsecond_, nanosecond_, unix_offset, is_local_time = parse_iso8601_time(parts[1])!
186}
187mut t := new(
188year: year
189month: month
190day: day
191hour: hour_
192minute: minute_
193second: second_
194nanosecond: nanosecond_
195)
196if is_local_time {
197return t // Time already local time
198}
199mut unix_time := t.unix
200if unix_offset < 0 {
201unix_time -= (-unix_offset)
202} else if unix_offset > 0 {
203unix_time += unix_offset
204}
205t = unix_nanosecond(i64(unix_time), t.nanosecond)
206return t
207}
208
209// parse_rfc2822 returns the time from a date string in RFC 2822 datetime format.
210pub fn parse_rfc2822(s string) !Time {
211if s == '' {
212return error_invalid_time(0, 'datetime string is empty')
213}
214fields := s.split(' ')
215if fields.len < 5 {
216return error_invalid_time(1, 'datetime string must have 5 components, has: ${fields.len}')
217}
218pos := months_string.index(fields[2]) or {
219return error_invalid_time(2, 'invalid month format')
220}
221mm := pos / 3 + 1
222unsafe {
223tmstr := malloc_noscan(s.len * 2)
224count := C.snprintf(&char(tmstr), (s.len * 2), c'%s-%02d-%s %s', fields[3].str,
225mm, fields[1].str, fields[4].str)
226return parse(tos(tmstr, count))
227}
228}
229
230// ----- iso8601 -----
231fn parse_iso8601_date(s string) !(int, int, int) {
232year, month, day, dummy := 0, 0, 0, u8(0)
233count := unsafe { C.sscanf(&char(s.str), c'%4d-%2d-%2d%c', &year, &month, &day, &dummy) }
234if count != 3 {
235return error_invalid_time(10, 'datetime string must have 3 components, but has ${count}')
236}
237if year > 9999 {
238return error_invalid_time(13, 'year must be smaller than 10000')
239}
240if month > 12 {
241return error_invalid_time(14, 'month must be smaller than 12')
242}
243if day > 31 {
244return error_invalid_time(15, 'day must be smaller than 31')
245}
246return year, month, day
247}
248
249fn parse_iso8601_time(s string) !(int, int, int, int, int, i64, bool) {
250hour_ := 0
251minute_ := 0
252second_ := 0
253mut microsecond_ := 0
254mut nanosecond_ := 0
255plus_min_z := `a`
256offset_hour := 0
257offset_minute := 0
258mut count := 0
259count = unsafe {
260C.sscanf(&char(s.str), c'%2d:%2d:%2d.%9d%c', &hour_, &minute_, &second_, &nanosecond_,
261&char(&plus_min_z))
262}
263if count == 5 && plus_min_z == `Z` {
264// normalise the nanoseconds:
265mut ndigits := 0
266if mut pos := s.index('.') {
267pos++
268for ; pos < s.len && s[pos].is_digit(); pos++ {
269ndigits++
270}
271}
272for ndigits < 9 {
273nanosecond_ *= 10
274ndigits++
275}
276microsecond_ = nanosecond_ / 1000
277} else {
278count = unsafe {
279C.sscanf(&char(s.str), c'%2d:%2d:%2d.%9d%c%2d:%2d', &hour_, &minute_, &second_,
280µsecond_, &char(&plus_min_z), &offset_hour, &offset_minute)
281}
282// Missread microsecond ([Sec Hour Minute].len == 3 < 4)
283if count < 4 {
284count = unsafe {
285C.sscanf(&char(s.str), c'%2d:%2d:%2d%c%2d:%2d', &hour_, &minute_, &second_,
286&char(&plus_min_z), &offset_hour, &offset_minute)
287}
288count++ // Increment count because skipped microsecond
289}
290if count < 4 {
291return error_invalid_time(10, 'malformed date')
292}
293nanosecond_ = microsecond_ * 1000
294}
295is_local_time := plus_min_z == `a` && count == 4
296is_utc := plus_min_z == `Z` && count == 5
297if !(count == 7 || is_local_time || is_utc) {
298return error_invalid_time(11, 'malformed date')
299}
300if plus_min_z != `+` && plus_min_z != `-` && !is_utc && !is_local_time {
301return error_invalid_time(12, 'missing timezone')
302}
303mut unix_offset := 0
304if offset_hour > 0 {
305unix_offset += 3600 * offset_hour
306}
307if offset_minute > 0 {
308unix_offset += 60 * offset_minute
309}
310if plus_min_z == `+` {
311unix_offset *= -1
312}
313// eprintln('parse_iso8601_time s: $s | hour_: $hour_ | minute_: $minute_ | second_: $second_ | microsecond_: $microsecond_ | nanosecond_: $nanosecond_ | unix_offset: $unix_offset | is_local_time: $is_local_time')
314return hour_, minute_, second_, microsecond_, nanosecond_, unix_offset, is_local_time
315}
316