Swift 5: How to calculate correct Date from provided string?

南笙酒味 提交于 2021-01-07 02:50:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!