Module: SugarCube::DateParser

Defined in:
lib/cocoa/sugarcube-nsdate/date_parser.rb

Class Method Summary collapse

Class Method Details

.iso8601(date_string) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/cocoa/sugarcube-nsdate/date_parser.rb', line 46

def iso8601(date_string)
  if defined? NSISO8601DateFormatter
    formatter = NSISO8601DateFormatter.alloc.init
    formatter.timeZone = NSTimeZone.timeZoneWithAbbreviation "UTC"
    date = formatter.dateFromString date_string
    return date if date
  end

  @@sugarcube_iso_detectors ||= [
    "yyyy-MM-dd'T'HH:mm:ss",
    "yyyy-MM-dd'T'HH:mm:ssZ",
    "yyyy-MM-dd'T'HH:mm:ss.S",
    "yyyy-MM-dd'T'HH:mm:ss.SZ",
    ].map do |date_format|
      formatter = NSDateFormatter.alloc.init
      formatter.timeZone = NSTimeZone.timeZoneWithAbbreviation "UTC"
      formatter.dateFormat = date_format
      formatter
    end
  return @@sugarcube_iso_detectors.inject(nil) { |date, formatter| date || formatter.dateFromString(date_string) }
end

.match(date_string) ⇒ Object

Parse a date into a raw match array for further processing



42
43
44
# File 'lib/cocoa/sugarcube-nsdate/date_parser.rb', line 42

def match(date_string)
  sugarcube_detect(date_string)
end

.parse_date(date_string) ⇒ Object

Parse a date string: E.g.:

SugarCube::DateParser.parse_date “There is a date in here tomorrow at 9:00 AM”

> 2013-02-20 09:00:00 -0800



10
11
12
13
14
15
16
# File 'lib/cocoa/sugarcube-nsdate/date_parser.rb', line 10

def parse_date(date_string)
  if result = iso8601(date_string)
    return result
  elsif result = sugarcube_detect(date_string).first
    return result.date
  end
end

.parse_duration(date_string) ⇒ Object

Parse a date string: E.g.:

SugarCube::DateParser.parse_date “You have a meeting from 9:00 AM to 3:00 PM”

> 21600.0

Divide by 3600.0 to get number of hours duration.



36
37
38
39
# File 'lib/cocoa/sugarcube-nsdate/date_parser.rb', line 36

def parse_duration(date_string)
  result = sugarcube_detect(date_string).first
  result && result.send(:duration)
end

.parse_time_zone(date_string) ⇒ Object

Parse time zone from date

SugarCube::DateParser.parse_date “There is a date in here tomorrow at 9:00 AM EDT”

Caveat: This is implemented per Apple documentation. I’ve never really

seen it work.


24
25
26
27
# File 'lib/cocoa/sugarcube-nsdate/date_parser.rb', line 24

def parse_time_zone(date_string)
  result = sugarcube_detect(date_string).first
  result && result.timeZone
end

.sugarcube_detect(date_string) ⇒ Object



68
69
70
71
# File 'lib/cocoa/sugarcube-nsdate/date_parser.rb', line 68

def sugarcube_detect(date_string)
  @@sugarcube_detector ||= NSDataDetector.dataDetectorWithTypes(NSTextCheckingTypeDate, error:Pointer.new(:object))
  return @@sugarcube_detector.matchesInString(date_string, options:0, range:NSMakeRange(0, date_string.length))
end