Class: Time

Inherits:
Object show all
Defined in:
opal/stdlib/time.rb,
opal/stdlib/json.rb,
opal/stdlib/native.rb

Overview

backtick_javascript: true

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.def_formatter(name, format, on_utc: false, utc_tz: nil, tz_format: nil, fractions: false, on: self) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'opal/stdlib/time.rb', line 28

def self.def_formatter(name, format, on_utc: false, utc_tz: nil, tz_format: nil, fractions: false, on: self)
  on.define_method name do |fdigits = 0|
    case self
    when defined?(::DateTime) && ::DateTime
      date = on_utc ? new_offset(0) : self
    when defined?(::Date) && ::Date
      date = ::Time.utc(year, month, day)
    when ::Time
      date = on_utc ? getutc : self
    end
    str = date.strftime(format)
    str += date.strftime(".%#{fdigits}N") if fractions && fdigits > 0
    if utc_tz
      str += utc ? utc_tz : date.strftime(tz_format)
    elsif tz_format
      str += date.strftime(tz_format)
    end
    str
  end
end

.parse(str) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'opal/stdlib/time.rb', line 4

def self.parse(str)
  %x{
    var d = Date.parse(str);
    if (d !== d) {
      // parsing failed, d is a NaN
      // probably str is not in ISO 8601 format, which is the only format, required to be supported by Javascript
      // try to make the format more like ISO or more like Chrome and parse again
      str = str.replace(/^(\d+)([\./])(\d+)([\./])?(\d+)?/, function(matched_sub, c1, c2, c3, c4, c5, offset, orig_string) {
        if ((c2 === c4) && c5) {
          // 2007.10.1 or 2007/10/1 are ok, but 2007/10.1 is not, convert to 2007-10-1
          return c1 + '-' + c3 + '-' + c5;
        } else if (c3 && !c4) {
          // 2007.10 or 2007/10
          // Chrome and Ruby can parse "2007/10", assuming its "2007-10-01", do the same
          return c1 + '-' + c3 + '-01';
        };
        return matched_sub;
      });
      d = Date.parse(str);
    }
    return new Date(d);
  }
end

Instance Method Details

#to_dateObject



55
56
57
# File 'opal/stdlib/time.rb', line 55

def to_date
  Date.wrap(self)
end

#to_datetimeObject



59
60
61
# File 'opal/stdlib/time.rb', line 59

def to_datetime
  DateTime.wrap(self)
end

#to_jsonObject



189
190
191
# File 'opal/stdlib/json.rb', line 189

def to_json
  strftime('%FT%T%z').to_json
end

#to_nObject



522
523
524
# File 'opal/stdlib/native.rb', line 522

def to_n
  self
end

#to_timeObject



63
64
65
# File 'opal/stdlib/time.rb', line 63

def to_time
  self
end