问题
I am not good at Swift so I would like to know how to calculate the current time is between two times.
I got the following response from the backend.
{"workHours":"M-F 9:00 - 18:00"}
How to get start
(9:00) time, end
(18:00) time from "M-F 11:00 - 20:00"
response using regular expression and DateFormatter?(I am not sure it is the correct way to get Date object from this kind of string, if not please recommend the best way and experience)
回答1:
You can use the following regex:
"^\\w-\\w\\s{1}(\\d{1,2}:\\d{2})\\s{1}-\\s{1}(\\d{1,2}:\\d{2})$"
break down
^ asserts position at start of a line
A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
- matches the character - literally (case sensitive)
A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
\s matches any whitespace character (equal to [\r\n\t\f\v]) {1} Quantifier — Matches exactly one time meaningless quantifier)
1st Capturing Group (\d{1,2}:\d{2})
\d{1,2} matches a digit (equal to [0-9])
{1,2} Quantifier — Matches between 1 and 2 times, as many times as possible, giving back as needed (greedy)
: matches the character : literally (case sensitive)
\d{2} matches a digit (equal to [0-9])
\s matches any whitespace character (equal to [\r\n\t\f\v]) {1} Quantifier — Matches exactly one time (meaningless quantifier)
- matches the character - literally (case sensitive)
\s{1} matches any whitespace character (equal to [\r\n\t\f\v ]) {1} Quantifier — Matches exactly one time (meaningless quantifier)
2nd Capturing Group (\d{1,2}:\d{2})
$ asserts position at the end of a line
let response = "M-F 11:00 - 20:00"
let pattern = "^[A-Z]-[A-Z]\\s{1}(\\d{1,2}:\\d{2})\\s{1}-\\s{1}(\\d{1,2}:\\d{2})$"
let regex = try! NSRegularExpression(pattern: pattern)
if let match = regex.matches(in: response, range: .init(response.startIndex..., in: response)).first,
match.numberOfRanges == 3 {
match.numberOfRanges
let start = match.range(at: 1)
print(response[Range(start, in: response)!])
let end = match.range(at: 2)
print(response[Range(end, in: response)!])
}
This will print
11:00
20:00
To get the time difference between start and end times (this considers that the resulting string will be a match of the above regex:
extension StringProtocol {
var minutesFromTime: Int {
let index = firstIndex(of: ":")!
return Int(self[..<index])! * 60 + Int(self[index...].dropFirst())!
}
}
let start = response[Range(match.range(at: 1), in: response)!]
let end = response[Range(match.range(at:2), in: response)!]
let minutes = end.minutesFromTime - start.minutesFromTime // 540
let hours = Double(minutes) / 60 // 9
来源:https://stackoverflow.com/questions/64235514/swift-5-how-to-calculate-correct-date-from-provided-string