Class: Time

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
opal/opal/corelib/time.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Comparable

#<, #<=, #>, #>=, #between?, normalize

Class Method Details

.at(seconds, frac = 0) ⇒ Object



13
14
15
# File 'opal/opal/corelib/time.rb', line 13

def self.at(seconds, frac = 0)
  `new Date(seconds * 1000 + frac)`
end

.gm(year, month = undefined, day = undefined, hour = undefined, minute = undefined, second = undefined, utc_offset = undefined) ⇒ Object Also known as: utc

Raises:



96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'opal/opal/corelib/time.rb', line 96

def self.gm(year, month = undefined, day = undefined, hour = undefined, minute = undefined, second = undefined, utc_offset = undefined)
  raise TypeError, 'missing year (got nil)' if year.nil?

  %x{
    if (month > 12 || day > 31 || hour > 24 || minute > 59 || second > 59) {
      #{raise ArgumentError};
    }

    var date = new Date(Date.UTC(year, (month || 1) - 1, (day || 1), (hour || 0), (minute || 0), (second || 0)));
    date.tz_offset = 0
    return date;
  }
end

.local(year, month = nil, day = nil, hour = nil, minute = nil, second = nil, millisecond = nil) ⇒ Object Also known as: mktime



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'opal/opal/corelib/time.rb', line 47

def self.local(year, month = nil, day = nil, hour = nil, minute = nil, second = nil, millisecond = nil)
  if `arguments.length === 10`
    %x{
      var args = $slice.call(arguments).reverse();

      second = args[9];
      minute = args[8];
      hour   = args[7];
      day    = args[6];
      month  = args[5];
      year   = args[4];
    }
  end

  year = year.kind_of?(String) ? year.to_i : Opal.coerce_to(year, Integer, :to_int)

  month = month.kind_of?(String) ? month.to_i : Opal.coerce_to(month || 1, Integer, :to_int)

  unless month.between?(1, 12)
    raise ArgumentError, "month out of range: #{month}"
  end

  day = day.kind_of?(String) ? day.to_i : Opal.coerce_to(day || 1, Integer, :to_int)

  unless day.between?(1, 31)
    raise ArgumentError, "day out of range: #{day}"
  end

  hour = hour.kind_of?(String) ? hour.to_i : Opal.coerce_to(hour || 0, Integer, :to_int)

  unless hour.between?(0, 24)
    raise ArgumentError, "hour out of range: #{hour}"
  end

  minute = minute.kind_of?(String) ? minute.to_i : Opal.coerce_to(minute || 0, Integer, :to_int)

  unless minute.between?(0, 59)
    raise ArgumentError, "minute out of range: #{minute}"
  end

  second = second.kind_of?(String)  ? second.to_i : Opal.coerce_to(second || 0, Integer, :to_int)

  unless second.between?(0, 59)
    raise ArgumentError, "second out of range: #{second}"
  end

  new(*[year, month, day, hour, minute, second].compact)
end

.new(year = undefined, month = undefined, day = undefined, hour = undefined, minute = undefined, second = undefined, utc_offset = undefined) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'opal/opal/corelib/time.rb', line 17

def self.new(year = undefined, month = undefined, day = undefined, hour = undefined, minute = undefined, second = undefined, utc_offset = undefined)
  %x{
    switch (arguments.length) {
      case 1:
        return new Date(year, 0);

      case 2:
        return new Date(year, month - 1);

      case 3:
        return new Date(year, month - 1, day);

      case 4:
        return new Date(year, month - 1, day, hour);

      case 5:
        return new Date(year, month - 1, day, hour, minute);

      case 6:
        return new Date(year, month - 1, day, hour, minute, second);

      case 7:
        return new Date(year, month - 1, day, hour, minute, second);

      default:
        return new Date();
    }
  }
end

.nowObject



115
116
117
# File 'opal/opal/corelib/time.rb', line 115

def self.now
  `new Date()`
end

Instance Method Details

#+(other) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'opal/opal/corelib/time.rb', line 119

def +(other)
  if Time === other
    raise TypeError, "time + time?"
  end

  other = Opal.coerce_to other, Integer, :to_int

  %x{
    var result = new Date(self.getTime() + (other * 1000));
    result.tz_offset = self.tz_offset;
    return result;
  }
end

#-(other) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'opal/opal/corelib/time.rb', line 133

def -(other)
  if Time === other
    `(self.getTime() - other.getTime()) / 1000`
  else
    other = Opal.coerce_to other, Integer, :to_int

    %x{
      var result = new Date(self.getTime() - (other * 1000));
      result.tz_offset = self.tz_offset;
      return result;
    }
  end
end

#<=>(other) ⇒ Object



147
148
149
# File 'opal/opal/corelib/time.rb', line 147

def <=>(other)
  to_f <=> other.to_f
end

#==(other) ⇒ Object



151
152
153
# File 'opal/opal/corelib/time.rb', line 151

def ==(other)
  `#{to_f} === #{other.to_f}`
end

#asctimeObject Also known as: ctime



155
156
157
# File 'opal/opal/corelib/time.rb', line 155

def asctime
  strftime '%a %b %e %H:%M:%S %Y'
end

#dayObject Also known as: mday



161
162
163
# File 'opal/opal/corelib/time.rb', line 161

def day
  `self.getDate()`
end

#eql?(other) ⇒ Boolean

Returns:



177
178
179
# File 'opal/opal/corelib/time.rb', line 177

def eql?(other)
  other.is_a?(Time) && (self <=> other).zero?
end

#friday?Boolean

Returns:



181
182
183
# File 'opal/opal/corelib/time.rb', line 181

def friday?
  `self.getDay() === 5`
end

#getgmObject



247
248
249
250
251
252
253
# File 'opal/opal/corelib/time.rb', line 247

def getgm
  %x{
    var result = new Date(self.getTime());
    result.tz_offset = 0;
    return result;
  }
end

#gmt?Boolean Also known as: utc?

Returns:



255
256
257
# File 'opal/opal/corelib/time.rb', line 255

def gmt?
  `self.tz_offset == 0`
end

#gmt_offsetObject



259
260
261
# File 'opal/opal/corelib/time.rb', line 259

def gmt_offset
  `-self.getTimezoneOffset() * 60`
end

#hourObject



185
186
187
# File 'opal/opal/corelib/time.rb', line 185

def hour
  `self.getHours()`
end

#inspectObject Also known as: to_s



189
190
191
192
193
194
195
# File 'opal/opal/corelib/time.rb', line 189

def inspect
  if utc?
    strftime '%Y-%m-%d %H:%M:%S UTC'
  else
    strftime '%Y-%m-%d %H:%M:%S %z'
  end
end

#isdstObject



173
174
175
# File 'opal/opal/corelib/time.rb', line 173

def isdst
  raise NotImplementedError
end

#minObject



199
200
201
# File 'opal/opal/corelib/time.rb', line 199

def min
  `self.getMinutes()`
end

#monObject Also known as: month



203
204
205
# File 'opal/opal/corelib/time.rb', line 203

def mon
  `self.getMonth() + 1`
end

#monday?Boolean

Returns:



207
208
209
# File 'opal/opal/corelib/time.rb', line 207

def monday?
  `self.getDay() === 1`
end

#saturday?Boolean

Returns:



213
214
215
# File 'opal/opal/corelib/time.rb', line 213

def saturday?
  `self.getDay() === 6`
end

#secObject



217
218
219
# File 'opal/opal/corelib/time.rb', line 217

def sec
  `self.getSeconds()`
end

#strftime(format) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'opal/opal/corelib/time.rb', line 263

def strftime(format)
  %x{
    return format.replace(/%([\-_#^0]*:{0,2})(\d+)?([EO]*)(.)/g, function(full, flags, width, _, conv) {
      var result = "",
          width  = parseInt(width),
          zero   = flags.indexOf('0') !== -1,
          pad    = flags.indexOf('-') === -1,
          blank  = flags.indexOf('_') !== -1,
          upcase = flags.indexOf('^') !== -1,
          invert = flags.indexOf('#') !== -1,
          colons = (flags.match(':') || []).length;

      if (zero && blank) {
        if (flags.indexOf('0') < flags.indexOf('_')) {
          zero = false;
        }
        else {
          blank = false;
        }
      }

      switch (conv) {
        case 'Y':
          result += self.getFullYear();
          break;

        case 'C':
          zero    = !blank;
          result += Match.round(self.getFullYear() / 100);
          break;

        case 'y':
          zero    = !blank;
          result += (self.getFullYear() % 100);
          break;

        case 'm':
          zero    = !blank;
          result += (self.getMonth() + 1);
          break;

        case 'B':
          result += long_months[self.getMonth()];
          break;

        case 'b':
        case 'h':
          blank   = !zero;
          result += short_months[self.getMonth()];
          break;

        case 'd':
          zero    = !blank
          result += self.getDate();
          break;

        case 'e':
          blank   = !zero
          result += self.getDate();
          break;

        case 'j':
          result += #{yday};
          break;

        case 'H':
          zero    = !blank;
          result += self.getHours();
          break;

        case 'k':
          blank   = !zero;
          result += self.getHours();
          break;

        case 'I':
          zero    = !blank;
          result += (self.getHours() % 12 || 12);
          break;

        case 'l':
          blank   = !zero;
          result += (self.getHours() % 12 || 12);
          break;

        case 'P':
          result += (self.getHours() >= 12 ? "pm" : "am");
          break;

        case 'p':
          result += (self.getHours() >= 12 ? "PM" : "AM");
          break;

        case 'M':
          zero    = !blank;
          result += self.getMinutes();
          break;

        case 'S':
          zero    = !blank;
          result += self.getSeconds();
          break;

        case 'L':
          zero    = !blank;
          width   = isNaN(width) ? 3 : width;
          result += self.getMilliseconds();
          break;

        case 'N':
          width   = isNaN(width) ? 9 : width;
          result += #{`self.getMilliseconds().toString()`.rjust(3, '0')};
          result  = #{`result`.ljust(`width`, '0')};
          break;

        case 'z':
          var offset  = self.getTimezoneOffset(),
              hours   = Math.floor(Math.abs(offset) / 60),
              minutes = Math.abs(offset) % 60;

          result += offset < 0 ? "+" : "-";
          result += hours < 10 ? "0" : "";
          result += hours;

          if (colons > 0) {
            result += ":";
          }

          result += minutes < 10 ? "0" : "";
          result += minutes;

          if (colons > 1) {
            result += ":00";
          }

          break;

        case 'Z':
          result += #{zone};
          break;

        case 'A':
          result += days_of_week[self.getDay()];
          break;

        case 'a':
          result += short_days[self.getDay()];
          break;

        case 'u':
          result += (self.getDay() + 1);
          break;

        case 'w':
          result += self.getDay();
          break;

        // TODO: week year
        // TODO: week number

        case 's':
          result += parseInt(self.getTime() / 1000)
          break;

        case 'n':
          result += "\n";
          break;

        case 't':
          result += "\t";
          break;

        case '%':
          result += "%";
          break;

        case 'c':
          result += #{strftime('%a %b %e %T %Y')};
          break;

        case 'D':
        case 'x':
          result += #{strftime('%m/%d/%y')};
          break;

        case 'F':
          result += #{strftime('%Y-%m-%d')};
          break;

        case 'v':
          result += #{strftime('%e-%^b-%4Y')};
          break;

        case 'r':
          result += #{strftime('%I:%M:%S %p')};
          break;

        case 'R':
          result += #{strftime('%H:%M')};
          break;

        case 'T':
        case 'X':
          result += #{strftime('%H:%M:%S')};
          break;

        default:
          return full;
      }

      if (upcase) {
        result = result.toUpperCase();
      }

      if (invert) {
        result = result.replace(/[A-Z]/, function(c) { c.toLowerCase() }).
                        replace(/[a-z]/, function(c) { c.toUpperCase() });
      }

      if (pad && (zero || blank)) {
        result = #{`result`.rjust(`isNaN(width) ? 2 : width`, `blank ? " " : "0"`)};
      }

      return result;
    });
  }
end

#sunday?Boolean

Returns:



491
492
493
# File 'opal/opal/corelib/time.rb', line 491

def sunday?
  `self.getDay() === 0`
end

#thursday?Boolean

Returns:



495
496
497
# File 'opal/opal/corelib/time.rb', line 495

def thursday?
  `self.getDay() === 4`
end

#to_aObject



499
500
501
# File 'opal/opal/corelib/time.rb', line 499

def to_a
  [sec, min, hour, day, month, year, wday, yday, isdst, zone]
end

#to_fObject



503
504
505
# File 'opal/opal/corelib/time.rb', line 503

def to_f
  `self.getTime() / 1000`
end

#to_iObject



507
508
509
# File 'opal/opal/corelib/time.rb', line 507

def to_i
  `parseInt(self.getTime() / 1000)`
end

#tuesday?Boolean

Returns:



513
514
515
# File 'opal/opal/corelib/time.rb', line 513

def tuesday?
  `self.getDay() === 2`
end

#usecObject



221
222
223
224
# File 'opal/opal/corelib/time.rb', line 221

def usec
  warn 'Microseconds are not supported'
  0
end

#utc_offsetObject



519
520
521
# File 'opal/opal/corelib/time.rb', line 519

def utc_offset
  `self.getTimezoneOffset() * -60`
end

#wdayObject



523
524
525
# File 'opal/opal/corelib/time.rb', line 523

def wday
  `self.getDay()`
end

#wednesday?Boolean

Returns:



527
528
529
# File 'opal/opal/corelib/time.rb', line 527

def wednesday?
  `self.getDay() === 3`
end

#ydayObject



165
166
167
168
169
170
171
# File 'opal/opal/corelib/time.rb', line 165

def yday
  %x{
    // http://javascript.about.com/library/bldayyear.htm
    var onejan = new Date(self.getFullYear(), 0, 1);
    return Math.ceil((self - onejan) / 86400000);
  }
end

#yearObject



531
532
533
# File 'opal/opal/corelib/time.rb', line 531

def year
  `self.getFullYear()`
end

#zoneObject



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'opal/opal/corelib/time.rb', line 226

def zone
  %x{
    var string = self.toString(),
        result;

    if (string.indexOf('(') == -1) {
      result = string.match(/[A-Z]{3,4}/)[0];
    }
    else {
      result = string.match(/\([^)]+\)/)[0].match(/[A-Z]/g).join('');
    }

    if (result == "GMT" && /(GMT\W*\d{4})/.test(string)) {
      return RegExp.$1;
    }
    else {
      return result;
    }
  }
end