Skip to content

Instantly share code, notes, and snippets.

@carlynorama
Last active September 3, 2020 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlynorama/77f7a8465cc6884368f0b8e3d3a34a7f to your computer and use it in GitHub Desktop.
Save carlynorama/77f7a8465cc6884368f0b8e3d3a34a7f to your computer and use it in GitHub Desktop.
Looks for date strings of multiple common formats
import Foundation
//https://nsdateformatter.com/
//https://stackoverflow.com/questions/3917250/converting-nsstring-to-nsdate-and-back-again
let testStrings = [
"Sep 2, 2020 8:08 PM",
"2018-09-12T14:11:54+0000",
"done: 2018-09-12T14:11:54+0000",
"2018-08-13 14:11:54 +0000",
"20:32 Wed, 30 Oct 2019",
"06.11.2020",
"2020.12.30",
"15 June 2020",
"Tomorrow",
"200831",
"200830 16:32"
]
let datePatterns = [
"yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd HH:mm:ss Z",
"d MMM yyyy HH:mm:ss Z",
"MMM d, yyyy h:mm a",
"MM-dd-yyyy HH:mm",
"HH:mm E, d MMM y",
"yyyy.mm.dd",
"dd.MM.yy",
"yyMMdd",
"yyMMdd HH:mm",
"d MMMM yyyy"
]
func dateFromDefinedString(_ candidateString:String) -> Date? {
let dateFormatter = DateFormatter()
for datePattern in datePatterns {
dateFormatter.dateFormat = datePattern
//print("testing formatter: \(dateFormatter.string(from: Date()))")
if let date = dateFormatter.date(from: candidateString) {
//print("date formatter: \(dateFormatter)")
return date
}
}
return nil
}
func dateFromString(_ candidateString:String) -> Date? {
var foundDate:Date?
let types: NSTextCheckingResult.CheckingType = [.date]
do {
let detector = try NSDataDetector(types: types.rawValue)
detector.enumerateMatches(
in: candidateString,
options: [],
range: NSRange(0..<candidateString.count)) { (result, _, _) in
foundDate = result?.date
}
} catch let error {
print(error)
}
return foundDate
}
for s in testStrings {
print(dateFromDefinedString(s))
}
print("---")
for s in testStrings {
print(dateFromString(s))
}
//RESULTS
//Optional(2020-09-03 03:08:00 +0000)
//Optional(2018-09-12 14:11:54 +0000)
//nil
//Optional(2018-08-13 14:11:54 +0000)
//Optional(2019-10-31 03:32:00 +0000)
//Optional(2020-11-06 08:00:00 +0000)
//Optional(2020-01-30 08:12:00 +0000)
//Optional(2020-06-15 07:00:00 +0000)
//nil
//Optional(2020-08-31 07:00:00 +0000)
//Optional(2020-08-30 23:32:00 +0000)
//---
//Optional(2020-09-03 03:08:00 +0000)
//Optional(2018-09-12 14:11:54 +0000)
//Optional(2018-09-12 14:11:54 +0000)
//Optional(2018-08-13 14:11:54 +0000)
//Optional(2019-10-31 03:32:00 +0000)
//Optional(2020-06-11 19:00:00 +0000)
//Optional(2020-12-30 20:00:00 +0000)
//Optional(2020-06-15 19:00:00 +0000)
//Optional(2020-09-03 19:00:00 +0000)
//nil
//Optional(2020-09-02 23:32:00 +0000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment