add time.parse_iso

pull/3197/head
yatsen1 2019-12-23 18:36:51 +08:00 committed by Alexander Medvednikov
parent d03f0ec294
commit 137a473bb7
2 changed files with 32 additions and 0 deletions

View File

@ -320,6 +320,22 @@ pub fn parse(s string) Time {
})
}
// `parse_iso` parses time in the following format: "Thu, 12 Dec 2019 06:07:45 GMT"
pub fn parse_iso(s string) Time {
fields := s.split(' ')
if fields.len < 5 {
return Time{}
}
pos := months_string.index(fields[2]) or { return Time{} }
mm := pos/3 + 1
tmstr := malloc(s.len*2)
count := int(C.sprintf(charptr(tmstr), '%s-%02d-%s %s'.str,
fields[3].str, mm, fields[1].str, fields[4].str))
return parse(tos(tmstr, count))
}
pub fn new_time(t Time) Time {
return {
t |

View File

@ -185,3 +185,19 @@ fn test_parse() {
&& t.hour == 12 && t.minute == 48 && t.second == 34
}
fn test_parse_iso() {
s1 := 'Thu, 12 Dec 2019 06:07:45 GMT'
t1 := time.parse_iso(s1)
assert t1.year == 2019 && t1.month == 12 && t1.day == 12
&& t1.hour == 6 && t1.minute == 7 && t1.second == 45
s2 := 'Thu 12 Dec 2019 06:07:45 +0800'
t2 := time.parse_iso(s2)
assert t2.year == 2019 && t2.month == 12 && t2.day == 12
&& t2.hour == 6 && t2.minute == 7 && t2.second == 45
s3 := 'Thu 12 Foo 2019 06:07:45 +0800'
t3 := time.parse_iso(s3)
assert t3.year == 0 && t3.month == 0 && t3.day == 0
&& t3.hour == 0 && t3.minute == 0 && t3.second == 0
}