[ruby/irb] Change debug test workaround only enabled when output is
[ruby.git] / time.c
blob3304b2f4f4856afd0e65bb02a8f8564e79d851c6
1 /**********************************************************************
3 time.c -
5 $Author$
6 created at: Tue Dec 28 14:31:59 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #define _DEFAULT_SOURCE
13 #define _BSD_SOURCE
14 #include "ruby/internal/config.h"
16 #include <errno.h>
17 #include <float.h>
18 #include <math.h>
19 #include <time.h>
20 #include <sys/types.h>
22 #ifdef HAVE_UNISTD_H
23 # include <unistd.h>
24 #endif
26 #ifdef HAVE_STRINGS_H
27 # include <strings.h>
28 #endif
30 #if defined(HAVE_SYS_TIME_H)
31 # include <sys/time.h>
32 #endif
34 #include "id.h"
35 #include "internal.h"
36 #include "internal/array.h"
37 #include "internal/hash.h"
38 #include "internal/compar.h"
39 #include "internal/numeric.h"
40 #include "internal/rational.h"
41 #include "internal/string.h"
42 #include "internal/time.h"
43 #include "internal/variable.h"
44 #include "ruby/encoding.h"
45 #include "timev.h"
47 #include "builtin.h"
49 static ID id_submicro, id_nano_num, id_nano_den, id_offset, id_zone;
50 static ID id_nanosecond, id_microsecond, id_millisecond, id_nsec, id_usec;
51 static ID id_local_to_utc, id_utc_to_local, id_find_timezone;
52 static ID id_year, id_mon, id_mday, id_hour, id_min, id_sec, id_isdst;
53 static VALUE str_utc, str_empty;
55 // used by deconstruct_keys
56 static VALUE sym_year, sym_month, sym_day, sym_yday, sym_wday;
57 static VALUE sym_hour, sym_min, sym_sec, sym_subsec, sym_dst, sym_zone;
59 #define id_quo idQuo
60 #define id_div idDiv
61 #define id_divmod idDivmod
62 #define id_name idName
63 #define UTC_ZONE Qundef
65 #define NDIV(x,y) (-(-((x)+1)/(y))-1)
66 #define NMOD(x,y) ((y)-(-((x)+1)%(y))-1)
67 #define DIV(n,d) ((n)<0 ? NDIV((n),(d)) : (n)/(d))
68 #define MOD(n,d) ((n)<0 ? NMOD((n),(d)) : (n)%(d))
69 #define VTM_WDAY_INITVAL (7)
70 #define VTM_ISDST_INITVAL (3)
72 static int
73 eq(VALUE x, VALUE y)
75 if (FIXNUM_P(x) && FIXNUM_P(y)) {
76 return x == y;
78 return RTEST(rb_funcall(x, idEq, 1, y));
81 static int
82 cmp(VALUE x, VALUE y)
84 if (FIXNUM_P(x) && FIXNUM_P(y)) {
85 if ((long)x < (long)y)
86 return -1;
87 if ((long)x > (long)y)
88 return 1;
89 return 0;
91 if (RB_BIGNUM_TYPE_P(x)) return FIX2INT(rb_big_cmp(x, y));
92 return rb_cmpint(rb_funcall(x, idCmp, 1, y), x, y);
95 #define ne(x,y) (!eq((x),(y)))
96 #define lt(x,y) (cmp((x),(y)) < 0)
97 #define gt(x,y) (cmp((x),(y)) > 0)
98 #define le(x,y) (cmp((x),(y)) <= 0)
99 #define ge(x,y) (cmp((x),(y)) >= 0)
101 static VALUE
102 addv(VALUE x, VALUE y)
104 if (FIXNUM_P(x) && FIXNUM_P(y)) {
105 return LONG2NUM(FIX2LONG(x) + FIX2LONG(y));
107 if (RB_BIGNUM_TYPE_P(x)) return rb_big_plus(x, y);
108 return rb_funcall(x, '+', 1, y);
111 static VALUE
112 subv(VALUE x, VALUE y)
114 if (FIXNUM_P(x) && FIXNUM_P(y)) {
115 return LONG2NUM(FIX2LONG(x) - FIX2LONG(y));
117 if (RB_BIGNUM_TYPE_P(x)) return rb_big_minus(x, y);
118 return rb_funcall(x, '-', 1, y);
121 static VALUE
122 mulv(VALUE x, VALUE y)
124 if (FIXNUM_P(x) && FIXNUM_P(y)) {
125 return rb_fix_mul_fix(x, y);
127 if (RB_BIGNUM_TYPE_P(x))
128 return rb_big_mul(x, y);
129 return rb_funcall(x, '*', 1, y);
132 static VALUE
133 divv(VALUE x, VALUE y)
135 if (FIXNUM_P(x) && FIXNUM_P(y)) {
136 return rb_fix_div_fix(x, y);
138 if (RB_BIGNUM_TYPE_P(x))
139 return rb_big_div(x, y);
140 return rb_funcall(x, id_div, 1, y);
143 static VALUE
144 modv(VALUE x, VALUE y)
146 if (FIXNUM_P(y)) {
147 if (FIX2LONG(y) == 0) rb_num_zerodiv();
148 if (FIXNUM_P(x)) return rb_fix_mod_fix(x, y);
150 if (RB_BIGNUM_TYPE_P(x)) return rb_big_modulo(x, y);
151 return rb_funcall(x, '%', 1, y);
154 #define neg(x) (subv(INT2FIX(0), (x)))
156 static VALUE
157 quor(VALUE x, VALUE y)
159 if (FIXNUM_P(x) && FIXNUM_P(y)) {
160 long a, b, c;
161 a = FIX2LONG(x);
162 b = FIX2LONG(y);
163 if (b == 0) rb_num_zerodiv();
164 if (a == FIXNUM_MIN && b == -1) return LONG2NUM(-a);
165 c = a / b;
166 if (c * b == a) {
167 return LONG2FIX(c);
170 return rb_numeric_quo(x, y);
173 static VALUE
174 quov(VALUE x, VALUE y)
176 VALUE ret = quor(x, y);
177 if (RB_TYPE_P(ret, T_RATIONAL) &&
178 RRATIONAL(ret)->den == INT2FIX(1)) {
179 ret = RRATIONAL(ret)->num;
181 return ret;
184 #define mulquov(x,y,z) (((y) == (z)) ? (x) : quov(mulv((x),(y)),(z)))
186 static void
187 divmodv(VALUE n, VALUE d, VALUE *q, VALUE *r)
189 VALUE tmp, ary;
190 if (FIXNUM_P(d)) {
191 if (FIX2LONG(d) == 0) rb_num_zerodiv();
192 if (FIXNUM_P(n)) {
193 rb_fix_divmod_fix(n, d, q, r);
194 return;
197 tmp = rb_funcall(n, id_divmod, 1, d);
198 ary = rb_check_array_type(tmp);
199 if (NIL_P(ary)) {
200 rb_raise(rb_eTypeError, "unexpected divmod result: into %"PRIsVALUE,
201 rb_obj_class(tmp));
203 *q = rb_ary_entry(ary, 0);
204 *r = rb_ary_entry(ary, 1);
207 #if SIZEOF_LONG == 8
208 # define INT64toNUM(x) LONG2NUM(x)
209 #elif defined(HAVE_LONG_LONG) && SIZEOF_LONG_LONG == 8
210 # define INT64toNUM(x) LL2NUM(x)
211 #endif
213 #if defined(HAVE_UINT64_T) && SIZEOF_LONG*2 <= SIZEOF_UINT64_T
214 typedef uint64_t uwideint_t;
215 typedef int64_t wideint_t;
216 typedef uint64_t WIDEVALUE;
217 typedef int64_t SIGNED_WIDEVALUE;
218 # define WIDEVALUE_IS_WIDER 1
219 # define UWIDEINT_MAX UINT64_MAX
220 # define WIDEINT_MAX INT64_MAX
221 # define WIDEINT_MIN INT64_MIN
222 # define FIXWINT_P(tv) ((tv) & 1)
223 # define FIXWVtoINT64(tv) RSHIFT((SIGNED_WIDEVALUE)(tv), 1)
224 # define INT64toFIXWV(wi) ((WIDEVALUE)((SIGNED_WIDEVALUE)(wi) << 1 | FIXNUM_FLAG))
225 # define FIXWV_MAX (((int64_t)1 << 62) - 1)
226 # define FIXWV_MIN (-((int64_t)1 << 62))
227 # define FIXWVABLE(wi) (POSFIXWVABLE(wi) && NEGFIXWVABLE(wi))
228 # define WINT2FIXWV(i) WIDEVAL_WRAP(INT64toFIXWV(i))
229 # define FIXWV2WINT(w) FIXWVtoINT64(WIDEVAL_GET(w))
230 #else
231 typedef unsigned long uwideint_t;
232 typedef long wideint_t;
233 typedef VALUE WIDEVALUE;
234 typedef SIGNED_VALUE SIGNED_WIDEVALUE;
235 # define WIDEVALUE_IS_WIDER 0
236 # define UWIDEINT_MAX ULONG_MAX
237 # define WIDEINT_MAX LONG_MAX
238 # define WIDEINT_MIN LONG_MIN
239 # define FIXWINT_P(v) FIXNUM_P(v)
240 # define FIXWV_MAX FIXNUM_MAX
241 # define FIXWV_MIN FIXNUM_MIN
242 # define FIXWVABLE(i) FIXABLE(i)
243 # define WINT2FIXWV(i) WIDEVAL_WRAP(LONG2FIX(i))
244 # define FIXWV2WINT(w) FIX2LONG(WIDEVAL_GET(w))
245 #endif
247 #define POSFIXWVABLE(wi) ((wi) < FIXWV_MAX+1)
248 #define NEGFIXWVABLE(wi) ((wi) >= FIXWV_MIN)
249 #define FIXWV_P(w) FIXWINT_P(WIDEVAL_GET(w))
250 #define MUL_OVERFLOW_FIXWV_P(a, b) MUL_OVERFLOW_SIGNED_INTEGER_P(a, b, FIXWV_MIN, FIXWV_MAX)
252 /* #define STRUCT_WIDEVAL */
253 #ifdef STRUCT_WIDEVAL
254 /* for type checking */
255 typedef struct {
256 WIDEVALUE value;
257 } wideval_t;
258 static inline wideval_t WIDEVAL_WRAP(WIDEVALUE v) { wideval_t w = { v }; return w; }
259 # define WIDEVAL_GET(w) ((w).value)
260 #else
261 typedef WIDEVALUE wideval_t;
262 # define WIDEVAL_WRAP(v) (v)
263 # define WIDEVAL_GET(w) (w)
264 #endif
266 #if WIDEVALUE_IS_WIDER
267 static inline wideval_t
268 wint2wv(wideint_t wi)
270 if (FIXWVABLE(wi))
271 return WINT2FIXWV(wi);
272 else
273 return WIDEVAL_WRAP(INT64toNUM(wi));
275 # define WINT2WV(wi) wint2wv(wi)
276 #else
277 # define WINT2WV(wi) WIDEVAL_WRAP(LONG2NUM(wi))
278 #endif
280 static inline VALUE
281 w2v(wideval_t w)
283 #if WIDEVALUE_IS_WIDER
284 if (FIXWV_P(w))
285 return INT64toNUM(FIXWV2WINT(w));
286 return (VALUE)WIDEVAL_GET(w);
287 #else
288 return WIDEVAL_GET(w);
289 #endif
292 #if WIDEVALUE_IS_WIDER
293 static wideval_t
294 v2w_bignum(VALUE v)
296 int sign;
297 uwideint_t u;
298 sign = rb_integer_pack(v, &u, 1, sizeof(u), 0,
299 INTEGER_PACK_NATIVE_BYTE_ORDER);
300 if (sign == 0)
301 return WINT2FIXWV(0);
302 else if (sign == -1) {
303 if (u <= -FIXWV_MIN)
304 return WINT2FIXWV(-(wideint_t)u);
306 else if (sign == +1) {
307 if (u <= FIXWV_MAX)
308 return WINT2FIXWV((wideint_t)u);
310 return WIDEVAL_WRAP(v);
312 #endif
314 static inline wideval_t
315 v2w(VALUE v)
317 if (RB_TYPE_P(v, T_RATIONAL)) {
318 if (RRATIONAL(v)->den != LONG2FIX(1))
319 return WIDEVAL_WRAP(v);
320 v = RRATIONAL(v)->num;
322 #if WIDEVALUE_IS_WIDER
323 if (FIXNUM_P(v)) {
324 return WIDEVAL_WRAP((WIDEVALUE)(SIGNED_WIDEVALUE)(long)v);
326 else if (RB_BIGNUM_TYPE_P(v) &&
327 rb_absint_size(v, NULL) <= sizeof(WIDEVALUE)) {
328 return v2w_bignum(v);
330 #endif
331 return WIDEVAL_WRAP(v);
334 static int
335 weq(wideval_t wx, wideval_t wy)
337 #if WIDEVALUE_IS_WIDER
338 if (FIXWV_P(wx) && FIXWV_P(wy)) {
339 return WIDEVAL_GET(wx) == WIDEVAL_GET(wy);
341 return RTEST(rb_funcall(w2v(wx), idEq, 1, w2v(wy)));
342 #else
343 return eq(WIDEVAL_GET(wx), WIDEVAL_GET(wy));
344 #endif
347 static int
348 wcmp(wideval_t wx, wideval_t wy)
350 VALUE x, y;
351 #if WIDEVALUE_IS_WIDER
352 if (FIXWV_P(wx) && FIXWV_P(wy)) {
353 wideint_t a, b;
354 a = FIXWV2WINT(wx);
355 b = FIXWV2WINT(wy);
356 if (a < b)
357 return -1;
358 if (a > b)
359 return 1;
360 return 0;
362 #endif
363 x = w2v(wx);
364 y = w2v(wy);
365 return cmp(x, y);
368 #define wne(x,y) (!weq((x),(y)))
369 #define wlt(x,y) (wcmp((x),(y)) < 0)
370 #define wgt(x,y) (wcmp((x),(y)) > 0)
371 #define wle(x,y) (wcmp((x),(y)) <= 0)
372 #define wge(x,y) (wcmp((x),(y)) >= 0)
374 static wideval_t
375 wadd(wideval_t wx, wideval_t wy)
377 #if WIDEVALUE_IS_WIDER
378 if (FIXWV_P(wx) && FIXWV_P(wy)) {
379 wideint_t r = FIXWV2WINT(wx) + FIXWV2WINT(wy);
380 return WINT2WV(r);
382 #endif
383 return v2w(addv(w2v(wx), w2v(wy)));
386 static wideval_t
387 wsub(wideval_t wx, wideval_t wy)
389 #if WIDEVALUE_IS_WIDER
390 if (FIXWV_P(wx) && FIXWV_P(wy)) {
391 wideint_t r = FIXWV2WINT(wx) - FIXWV2WINT(wy);
392 return WINT2WV(r);
394 #endif
395 return v2w(subv(w2v(wx), w2v(wy)));
398 static wideval_t
399 wmul(wideval_t wx, wideval_t wy)
401 #if WIDEVALUE_IS_WIDER
402 if (FIXWV_P(wx) && FIXWV_P(wy)) {
403 if (!MUL_OVERFLOW_FIXWV_P(FIXWV2WINT(wx), FIXWV2WINT(wy)))
404 return WINT2WV(FIXWV2WINT(wx) * FIXWV2WINT(wy));
406 #endif
407 return v2w(mulv(w2v(wx), w2v(wy)));
410 static wideval_t
411 wquo(wideval_t wx, wideval_t wy)
413 #if WIDEVALUE_IS_WIDER
414 if (FIXWV_P(wx) && FIXWV_P(wy)) {
415 wideint_t a, b, c;
416 a = FIXWV2WINT(wx);
417 b = FIXWV2WINT(wy);
418 if (b == 0) rb_num_zerodiv();
419 c = a / b;
420 if (c * b == a) {
421 return WINT2WV(c);
424 #endif
425 return v2w(quov(w2v(wx), w2v(wy)));
428 #define wmulquo(x,y,z) ((WIDEVAL_GET(y) == WIDEVAL_GET(z)) ? (x) : wquo(wmul((x),(y)),(z)))
429 #define wmulquoll(x,y,z) (((y) == (z)) ? (x) : wquo(wmul((x),WINT2WV(y)),WINT2WV(z)))
431 #if WIDEVALUE_IS_WIDER
432 static int
433 wdivmod0(wideval_t wn, wideval_t wd, wideval_t *wq, wideval_t *wr)
435 if (FIXWV_P(wn) && FIXWV_P(wd)) {
436 wideint_t n, d, q, r;
437 d = FIXWV2WINT(wd);
438 if (d == 0) rb_num_zerodiv();
439 if (d == 1) {
440 *wq = wn;
441 *wr = WINT2FIXWV(0);
442 return 1;
444 if (d == -1) {
445 wideint_t xneg = -FIXWV2WINT(wn);
446 *wq = WINT2WV(xneg);
447 *wr = WINT2FIXWV(0);
448 return 1;
450 n = FIXWV2WINT(wn);
451 if (n == 0) {
452 *wq = WINT2FIXWV(0);
453 *wr = WINT2FIXWV(0);
454 return 1;
456 q = n / d;
457 r = n % d;
458 if (d > 0 ? r < 0 : r > 0) {
459 q -= 1;
460 r += d;
462 *wq = WINT2FIXWV(q);
463 *wr = WINT2FIXWV(r);
464 return 1;
466 return 0;
468 #endif
470 static void
471 wdivmod(wideval_t wn, wideval_t wd, wideval_t *wq, wideval_t *wr)
473 VALUE vq, vr;
474 #if WIDEVALUE_IS_WIDER
475 if (wdivmod0(wn, wd, wq, wr)) return;
476 #endif
477 divmodv(w2v(wn), w2v(wd), &vq, &vr);
478 *wq = v2w(vq);
479 *wr = v2w(vr);
482 static void
483 wmuldivmod(wideval_t wx, wideval_t wy, wideval_t wz, wideval_t *wq, wideval_t *wr)
485 if (WIDEVAL_GET(wy) == WIDEVAL_GET(wz)) {
486 *wq = wx;
487 *wr = WINT2FIXWV(0);
488 return;
490 wdivmod(wmul(wx,wy), wz, wq, wr);
493 static wideval_t
494 wdiv(wideval_t wx, wideval_t wy)
496 #if WIDEVALUE_IS_WIDER
497 wideval_t q, dmy;
498 if (wdivmod0(wx, wy, &q, &dmy)) return q;
499 #endif
500 return v2w(divv(w2v(wx), w2v(wy)));
503 static wideval_t
504 wmod(wideval_t wx, wideval_t wy)
506 #if WIDEVALUE_IS_WIDER
507 wideval_t r, dmy;
508 if (wdivmod0(wx, wy, &dmy, &r)) return r;
509 #endif
510 return v2w(modv(w2v(wx), w2v(wy)));
513 static VALUE
514 num_exact_check(VALUE v)
516 VALUE tmp;
518 switch (TYPE(v)) {
519 case T_FIXNUM:
520 case T_BIGNUM:
521 tmp = v;
522 break;
524 case T_RATIONAL:
525 tmp = rb_rational_canonicalize(v);
526 break;
528 default:
529 if (!UNDEF_P(tmp = rb_check_funcall(v, idTo_r, 0, NULL))) {
530 /* test to_int method availability to reject non-Numeric
531 * objects such as String, Time, etc which have to_r method. */
532 if (!rb_respond_to(v, idTo_int)) {
533 /* FALLTHROUGH */
535 else if (RB_INTEGER_TYPE_P(tmp)) {
536 break;
538 else if (RB_TYPE_P(tmp, T_RATIONAL)) {
539 tmp = rb_rational_canonicalize(tmp);
540 break;
543 else if (!NIL_P(tmp = rb_check_to_int(v))) {
544 return tmp;
547 case T_NIL:
548 case T_STRING:
549 return Qnil;
551 ASSUME(!NIL_P(tmp));
552 return tmp;
555 NORETURN(static void num_exact_fail(VALUE v));
556 static void
557 num_exact_fail(VALUE v)
559 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into an exact number",
560 rb_obj_class(v));
563 static VALUE
564 num_exact(VALUE v)
566 VALUE num = num_exact_check(v);
567 if (NIL_P(num)) num_exact_fail(v);
568 return num;
571 /* time_t */
573 static wideval_t
574 rb_time_magnify(wideval_t w)
576 return wmul(w, WINT2FIXWV(TIME_SCALE));
579 static VALUE
580 rb_time_unmagnify_to_rational(wideval_t w)
582 return quor(w2v(w), INT2FIX(TIME_SCALE));
585 static wideval_t
586 rb_time_unmagnify(wideval_t w)
588 return v2w(rb_time_unmagnify_to_rational(w));
591 static VALUE
592 rb_time_unmagnify_to_float(wideval_t w)
594 VALUE v;
595 #if WIDEVALUE_IS_WIDER
596 if (FIXWV_P(w)) {
597 wideint_t a, b, c;
598 a = FIXWV2WINT(w);
599 b = TIME_SCALE;
600 c = a / b;
601 if (c * b == a) {
602 return DBL2NUM((double)c);
604 v = DBL2NUM((double)FIXWV2WINT(w));
605 return quov(v, DBL2NUM(TIME_SCALE));
607 #endif
608 v = w2v(w);
609 if (RB_TYPE_P(v, T_RATIONAL))
610 return rb_Float(quov(v, INT2FIX(TIME_SCALE)));
611 else
612 return quov(v, DBL2NUM(TIME_SCALE));
615 static void
616 split_second(wideval_t timew, wideval_t *timew_p, VALUE *subsecx_p)
618 wideval_t q, r;
619 wdivmod(timew, WINT2FIXWV(TIME_SCALE), &q, &r);
620 *timew_p = q;
621 *subsecx_p = w2v(r);
624 static wideval_t
625 timet2wv(time_t t)
627 #if WIDEVALUE_IS_WIDER
628 if (TIMET_MIN == 0) {
629 uwideint_t wi = (uwideint_t)t;
630 if (wi <= FIXWV_MAX) {
631 return WINT2FIXWV(wi);
634 else {
635 wideint_t wi = (wideint_t)t;
636 if (FIXWV_MIN <= wi && wi <= FIXWV_MAX) {
637 return WINT2FIXWV(wi);
640 #endif
641 return v2w(TIMET2NUM(t));
643 #define TIMET2WV(t) timet2wv(t)
645 static time_t
646 wv2timet(wideval_t w)
648 #if WIDEVALUE_IS_WIDER
649 if (FIXWV_P(w)) {
650 wideint_t wi = FIXWV2WINT(w);
651 if (TIMET_MIN == 0) {
652 if (wi < 0)
653 rb_raise(rb_eRangeError, "negative value to convert into 'time_t'");
654 if (TIMET_MAX < (uwideint_t)wi)
655 rb_raise(rb_eRangeError, "too big to convert into 'time_t'");
657 else {
658 if (wi < TIMET_MIN || TIMET_MAX < wi)
659 rb_raise(rb_eRangeError, "too big to convert into 'time_t'");
661 return (time_t)wi;
663 #endif
664 return NUM2TIMET(w2v(w));
666 #define WV2TIMET(t) wv2timet(t)
668 VALUE rb_cTime;
669 static VALUE rb_cTimeTM;
671 static int obj2int(VALUE obj);
672 static uint32_t obj2ubits(VALUE obj, unsigned int bits);
673 static VALUE obj2vint(VALUE obj);
674 static uint32_t month_arg(VALUE arg);
675 static VALUE validate_utc_offset(VALUE utc_offset);
676 static VALUE validate_zone_name(VALUE zone_name);
677 static void validate_vtm(struct vtm *vtm);
678 static void vtm_add_day(struct vtm *vtm, int day);
679 static uint32_t obj2subsecx(VALUE obj, VALUE *subsecx);
681 static VALUE time_gmtime(VALUE);
682 static VALUE time_localtime(VALUE);
683 static VALUE time_fixoff(VALUE);
684 static VALUE time_zonelocal(VALUE time, VALUE off);
686 static time_t timegm_noleapsecond(struct tm *tm);
687 static int tmcmp(struct tm *a, struct tm *b);
688 static int vtmcmp(struct vtm *a, struct vtm *b);
689 static const char *find_time_t(struct tm *tptr, int utc_p, time_t *tp);
691 static struct vtm *localtimew(wideval_t timew, struct vtm *result);
693 static int leap_year_p(long y);
694 #define leap_year_v_p(y) leap_year_p(NUM2LONG(modv((y), INT2FIX(400))))
696 static VALUE tm_from_time(VALUE klass, VALUE time);
698 bool ruby_tz_uptodate_p;
700 void
701 ruby_reset_timezone(void)
703 ruby_tz_uptodate_p = false;
704 ruby_reset_leap_second_info();
707 static void
708 update_tz(void)
710 if (ruby_tz_uptodate_p) return;
711 ruby_tz_uptodate_p = true;
712 tzset();
715 static struct tm *
716 rb_localtime_r(const time_t *t, struct tm *result)
718 #if defined __APPLE__ && defined __LP64__
719 if (*t != (time_t)(int)*t) return NULL;
720 #endif
721 update_tz();
722 #ifdef HAVE_GMTIME_R
723 result = localtime_r(t, result);
724 #else
726 struct tm *tmp = localtime(t);
727 if (tmp) *result = *tmp;
729 #endif
730 #if defined(HAVE_MKTIME) && defined(LOCALTIME_OVERFLOW_PROBLEM)
731 if (result) {
732 long gmtoff1 = 0;
733 long gmtoff2 = 0;
734 struct tm tmp = *result;
735 time_t t2;
736 t2 = mktime(&tmp);
737 # if defined(HAVE_STRUCT_TM_TM_GMTOFF)
738 gmtoff1 = result->tm_gmtoff;
739 gmtoff2 = tmp.tm_gmtoff;
740 # endif
741 if (*t + gmtoff1 != t2 + gmtoff2)
742 result = NULL;
744 #endif
745 return result;
747 #define LOCALTIME(tm, result) rb_localtime_r((tm), &(result))
749 #ifndef HAVE_STRUCT_TM_TM_GMTOFF
750 static struct tm *
751 rb_gmtime_r(const time_t *t, struct tm *result)
753 #ifdef HAVE_GMTIME_R
754 result = gmtime_r(t, result);
755 #else
756 struct tm *tmp = gmtime(t);
757 if (tmp) *result = *tmp;
758 #endif
759 #if defined(HAVE_TIMEGM) && defined(LOCALTIME_OVERFLOW_PROBLEM)
760 if (result && *t != timegm(result)) {
761 return NULL;
763 #endif
764 return result;
766 # define GMTIME(tm, result) rb_gmtime_r((tm), &(result))
767 #endif
769 static const int16_t common_year_yday_offset[] = {
771 -1 + 31,
772 -1 + 31 + 28,
773 -1 + 31 + 28 + 31,
774 -1 + 31 + 28 + 31 + 30,
775 -1 + 31 + 28 + 31 + 30 + 31,
776 -1 + 31 + 28 + 31 + 30 + 31 + 30,
777 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31,
778 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
779 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
780 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
781 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30
782 /* 1 2 3 4 5 6 7 8 9 10 11 */
784 static const int16_t leap_year_yday_offset[] = {
786 -1 + 31,
787 -1 + 31 + 29,
788 -1 + 31 + 29 + 31,
789 -1 + 31 + 29 + 31 + 30,
790 -1 + 31 + 29 + 31 + 30 + 31,
791 -1 + 31 + 29 + 31 + 30 + 31 + 30,
792 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31,
793 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31,
794 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
795 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
796 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30
797 /* 1 2 3 4 5 6 7 8 9 10 11 */
800 static const int8_t common_year_days_in_month[] = {
801 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
803 static const int8_t leap_year_days_in_month[] = {
804 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
807 #define days_in_month_of(leap) ((leap) ? leap_year_days_in_month : common_year_days_in_month)
808 #define days_in_month_in(y) days_in_month_of(leap_year_p(y))
809 #define days_in_month_in_v(y) days_in_month_of(leap_year_v_p(y))
811 #define M28(m) \
812 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
813 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
814 (m),(m),(m),(m),(m),(m),(m),(m)
815 #define M29(m) \
816 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
817 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
818 (m),(m),(m),(m),(m),(m),(m),(m),(m)
819 #define M30(m) \
820 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
821 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
822 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m)
823 #define M31(m) \
824 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
825 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
826 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), (m)
828 static const uint8_t common_year_mon_of_yday[] = {
829 M31(1), M28(2), M31(3), M30(4), M31(5), M30(6),
830 M31(7), M31(8), M30(9), M31(10), M30(11), M31(12)
832 static const uint8_t leap_year_mon_of_yday[] = {
833 M31(1), M29(2), M31(3), M30(4), M31(5), M30(6),
834 M31(7), M31(8), M30(9), M31(10), M30(11), M31(12)
837 #undef M28
838 #undef M29
839 #undef M30
840 #undef M31
842 #define D28 \
843 1,2,3,4,5,6,7,8,9, \
844 10,11,12,13,14,15,16,17,18,19, \
845 20,21,22,23,24,25,26,27,28
846 #define D29 \
847 1,2,3,4,5,6,7,8,9, \
848 10,11,12,13,14,15,16,17,18,19, \
849 20,21,22,23,24,25,26,27,28,29
850 #define D30 \
851 1,2,3,4,5,6,7,8,9, \
852 10,11,12,13,14,15,16,17,18,19, \
853 20,21,22,23,24,25,26,27,28,29,30
854 #define D31 \
855 1,2,3,4,5,6,7,8,9, \
856 10,11,12,13,14,15,16,17,18,19, \
857 20,21,22,23,24,25,26,27,28,29,30,31
859 static const uint8_t common_year_mday_of_yday[] = {
860 /* 1 2 3 4 5 6 7 8 9 10 11 12 */
861 D31, D28, D31, D30, D31, D30, D31, D31, D30, D31, D30, D31
863 static const uint8_t leap_year_mday_of_yday[] = {
864 D31, D29, D31, D30, D31, D30, D31, D31, D30, D31, D30, D31
867 #undef D28
868 #undef D29
869 #undef D30
870 #undef D31
872 static int
873 calc_tm_yday(long tm_year, int tm_mon, int tm_mday)
875 int tm_year_mod400 = (int)MOD(tm_year, 400);
876 int tm_yday = tm_mday;
878 if (leap_year_p(tm_year_mod400 + 1900))
879 tm_yday += leap_year_yday_offset[tm_mon];
880 else
881 tm_yday += common_year_yday_offset[tm_mon];
883 return tm_yday;
886 static wideval_t
887 timegmw_noleapsecond(struct vtm *vtm)
889 VALUE year1900;
890 VALUE q400, r400;
891 int year_mod400;
892 int yday;
893 long days_in400;
894 VALUE vdays, ret;
895 wideval_t wret;
897 year1900 = subv(vtm->year, INT2FIX(1900));
899 divmodv(year1900, INT2FIX(400), &q400, &r400);
900 year_mod400 = NUM2INT(r400);
902 yday = calc_tm_yday(year_mod400, vtm->mon-1, vtm->mday);
905 * `Seconds Since the Epoch' in SUSv3:
906 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
907 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
908 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
910 ret = LONG2NUM(vtm->sec
911 + vtm->min*60
912 + vtm->hour*3600);
913 days_in400 = yday
914 - 70*365
915 + DIV(year_mod400 - 69, 4)
916 - DIV(year_mod400 - 1, 100)
917 + (year_mod400 + 299) / 400;
918 vdays = LONG2NUM(days_in400);
919 vdays = addv(vdays, mulv(q400, INT2FIX(97)));
920 vdays = addv(vdays, mulv(year1900, INT2FIX(365)));
921 wret = wadd(rb_time_magnify(v2w(ret)), wmul(rb_time_magnify(v2w(vdays)), WINT2FIXWV(86400)));
922 wret = wadd(wret, v2w(vtm->subsecx));
924 return wret;
927 static VALUE
928 zone_str(const char *zone)
930 const char *p;
931 int ascii_only = 1;
932 VALUE str;
933 size_t len;
935 if (zone == NULL) {
936 return rb_fstring_lit("(NO-TIMEZONE-ABBREVIATION)");
939 for (p = zone; *p; p++)
940 if (!ISASCII(*p)) {
941 ascii_only = 0;
942 break;
944 len = p - zone + strlen(p);
945 if (ascii_only) {
946 str = rb_usascii_str_new(zone, len);
948 else {
949 str = rb_enc_str_new(zone, len, rb_locale_encoding());
951 return rb_fstring(str);
954 static void
955 gmtimew_noleapsecond(wideval_t timew, struct vtm *vtm)
957 VALUE v;
958 int n, x, y;
959 int wday;
960 VALUE timev;
961 wideval_t timew2, w, w2;
962 VALUE subsecx;
964 vtm->isdst = 0;
966 split_second(timew, &timew2, &subsecx);
967 vtm->subsecx = subsecx;
969 wdivmod(timew2, WINT2FIXWV(86400), &w2, &w);
970 timev = w2v(w2);
971 v = w2v(w);
973 wday = NUM2INT(modv(timev, INT2FIX(7)));
974 vtm->wday = (wday + 4) % 7;
976 n = NUM2INT(v);
977 vtm->sec = n % 60; n = n / 60;
978 vtm->min = n % 60; n = n / 60;
979 vtm->hour = n;
981 /* 97 leap days in the 400 year cycle */
982 divmodv(timev, INT2FIX(400*365 + 97), &timev, &v);
983 vtm->year = mulv(timev, INT2FIX(400));
985 /* n is the days in the 400 year cycle.
986 * the start of the cycle is 1970-01-01. */
988 n = NUM2INT(v);
989 y = 1970;
991 /* 30 years including 7 leap days (1972, 1976, ... 1996),
992 * 31 days in January 2000 and
993 * 29 days in February 2000
994 * from 1970-01-01 to 2000-02-29 */
995 if (30*365+7+31+29-1 <= n) {
996 /* 2000-02-29 or after */
997 if (n < 31*365+8) {
998 /* 2000-02-29 to 2000-12-31 */
999 y += 30;
1000 n -= 30*365+7;
1001 goto found;
1003 else {
1004 /* 2001-01-01 or after */
1005 n -= 1;
1009 x = n / (365*100 + 24);
1010 n = n % (365*100 + 24);
1011 y += x * 100;
1012 if (30*365+7+31+29-1 <= n) {
1013 if (n < 31*365+7) {
1014 y += 30;
1015 n -= 30*365+7;
1016 goto found;
1018 else
1019 n += 1;
1022 x = n / (365*4 + 1);
1023 n = n % (365*4 + 1);
1024 y += x * 4;
1025 if (365*2+31+29-1 <= n) {
1026 if (n < 365*2+366) {
1027 y += 2;
1028 n -= 365*2;
1029 goto found;
1031 else
1032 n -= 1;
1035 x = n / 365;
1036 n = n % 365;
1037 y += x;
1039 found:
1040 vtm->yday = n+1;
1041 vtm->year = addv(vtm->year, INT2NUM(y));
1043 if (leap_year_p(y)) {
1044 vtm->mon = leap_year_mon_of_yday[n];
1045 vtm->mday = leap_year_mday_of_yday[n];
1047 else {
1048 vtm->mon = common_year_mon_of_yday[n];
1049 vtm->mday = common_year_mday_of_yday[n];
1052 vtm->utc_offset = INT2FIX(0);
1053 vtm->zone = str_utc;
1056 static struct tm *
1057 gmtime_with_leapsecond(const time_t *timep, struct tm *result)
1059 #if defined(HAVE_STRUCT_TM_TM_GMTOFF)
1060 /* 4.4BSD counts leap seconds only with localtime, not with gmtime. */
1061 struct tm *t;
1062 int sign;
1063 int gmtoff_sec, gmtoff_min, gmtoff_hour, gmtoff_day;
1064 long gmtoff;
1065 t = LOCALTIME(timep, *result);
1066 if (t == NULL)
1067 return NULL;
1069 /* subtract gmtoff */
1070 if (t->tm_gmtoff < 0) {
1071 sign = 1;
1072 gmtoff = -t->tm_gmtoff;
1074 else {
1075 sign = -1;
1076 gmtoff = t->tm_gmtoff;
1078 gmtoff_sec = (int)(gmtoff % 60);
1079 gmtoff = gmtoff / 60;
1080 gmtoff_min = (int)(gmtoff % 60);
1081 gmtoff = gmtoff / 60;
1082 gmtoff_hour = (int)gmtoff; /* <= 12 */
1084 gmtoff_sec *= sign;
1085 gmtoff_min *= sign;
1086 gmtoff_hour *= sign;
1088 gmtoff_day = 0;
1090 if (gmtoff_sec) {
1091 /* If gmtoff_sec == 0, don't change result->tm_sec.
1092 * It may be 60 which is a leap second. */
1093 result->tm_sec += gmtoff_sec;
1094 if (result->tm_sec < 0) {
1095 result->tm_sec += 60;
1096 gmtoff_min -= 1;
1098 if (60 <= result->tm_sec) {
1099 result->tm_sec -= 60;
1100 gmtoff_min += 1;
1103 if (gmtoff_min) {
1104 result->tm_min += gmtoff_min;
1105 if (result->tm_min < 0) {
1106 result->tm_min += 60;
1107 gmtoff_hour -= 1;
1109 if (60 <= result->tm_min) {
1110 result->tm_min -= 60;
1111 gmtoff_hour += 1;
1114 if (gmtoff_hour) {
1115 result->tm_hour += gmtoff_hour;
1116 if (result->tm_hour < 0) {
1117 result->tm_hour += 24;
1118 gmtoff_day = -1;
1120 if (24 <= result->tm_hour) {
1121 result->tm_hour -= 24;
1122 gmtoff_day = 1;
1126 if (gmtoff_day) {
1127 if (gmtoff_day < 0) {
1128 if (result->tm_yday == 0) {
1129 result->tm_mday = 31;
1130 result->tm_mon = 11; /* December */
1131 result->tm_year--;
1132 result->tm_yday = leap_year_p(result->tm_year + 1900) ? 365 : 364;
1134 else if (result->tm_mday == 1) {
1135 const int8_t *days_in_month = days_in_month_in(result->tm_year + 1900);
1136 result->tm_mon--;
1137 result->tm_mday = days_in_month[result->tm_mon];
1138 result->tm_yday--;
1140 else {
1141 result->tm_mday--;
1142 result->tm_yday--;
1144 result->tm_wday = (result->tm_wday + 6) % 7;
1146 else {
1147 int leap = leap_year_p(result->tm_year + 1900);
1148 if (result->tm_yday == (leap ? 365 : 364)) {
1149 result->tm_year++;
1150 result->tm_mon = 0; /* January */
1151 result->tm_mday = 1;
1152 result->tm_yday = 0;
1154 else if (result->tm_mday == days_in_month_of(leap)[result->tm_mon]) {
1155 result->tm_mon++;
1156 result->tm_mday = 1;
1157 result->tm_yday++;
1159 else {
1160 result->tm_mday++;
1161 result->tm_yday++;
1163 result->tm_wday = (result->tm_wday + 1) % 7;
1166 result->tm_isdst = 0;
1167 result->tm_gmtoff = 0;
1168 #if defined(HAVE_TM_ZONE)
1169 result->tm_zone = (char *)"UTC";
1170 #endif
1171 return result;
1172 #else
1173 return GMTIME(timep, *result);
1174 #endif
1177 static long this_year = 0;
1178 static time_t known_leap_seconds_limit;
1179 static int number_of_leap_seconds_known;
1181 static void
1182 init_leap_second_info(void)
1185 * leap seconds are determined by IERS.
1186 * It is announced 6 months before the leap second.
1187 * So no one knows leap seconds in the future after the next year.
1189 if (this_year == 0) {
1190 time_t now;
1191 struct tm *tm, result;
1192 struct vtm vtm;
1193 wideval_t timew;
1194 now = time(NULL);
1195 #ifdef HAVE_GMTIME_R
1196 gmtime_r(&now, &result);
1197 #else
1198 gmtime(&now);
1199 #endif
1200 tm = gmtime_with_leapsecond(&now, &result);
1201 if (!tm) return;
1202 this_year = tm->tm_year;
1204 if (TIMET_MAX - now < (time_t)(366*86400))
1205 known_leap_seconds_limit = TIMET_MAX;
1206 else
1207 known_leap_seconds_limit = now + (time_t)(366*86400);
1209 if (!gmtime_with_leapsecond(&known_leap_seconds_limit, &result))
1210 return;
1212 vtm.year = LONG2NUM(result.tm_year + 1900);
1213 vtm.mon = result.tm_mon + 1;
1214 vtm.mday = result.tm_mday;
1215 vtm.hour = result.tm_hour;
1216 vtm.min = result.tm_min;
1217 vtm.sec = result.tm_sec;
1218 vtm.subsecx = INT2FIX(0);
1219 vtm.utc_offset = INT2FIX(0);
1221 timew = timegmw_noleapsecond(&vtm);
1223 number_of_leap_seconds_known = NUM2INT(w2v(wsub(TIMET2WV(known_leap_seconds_limit), rb_time_unmagnify(timew))));
1227 /* Use this if you want to re-run init_leap_second_info() */
1228 void
1229 ruby_reset_leap_second_info(void)
1231 this_year = 0;
1234 static wideval_t
1235 timegmw(struct vtm *vtm)
1237 wideval_t timew;
1238 struct tm tm;
1239 time_t t;
1240 const char *errmsg;
1242 /* The first leap second is 1972-06-30 23:59:60 UTC.
1243 * No leap seconds before. */
1244 if (gt(INT2FIX(1972), vtm->year))
1245 return timegmw_noleapsecond(vtm);
1247 init_leap_second_info();
1249 timew = timegmw_noleapsecond(vtm);
1252 if (number_of_leap_seconds_known == 0) {
1253 /* When init_leap_second_info() is executed, the timezone doesn't have
1254 * leap second information. Disable leap second for calculating gmtime.
1256 return timew;
1258 else if (wlt(rb_time_magnify(TIMET2WV(known_leap_seconds_limit)), timew)) {
1259 return wadd(timew, rb_time_magnify(WINT2WV(number_of_leap_seconds_known)));
1262 tm.tm_year = rb_long2int(NUM2LONG(vtm->year) - 1900);
1263 tm.tm_mon = vtm->mon - 1;
1264 tm.tm_mday = vtm->mday;
1265 tm.tm_hour = vtm->hour;
1266 tm.tm_min = vtm->min;
1267 tm.tm_sec = vtm->sec;
1268 tm.tm_isdst = 0;
1270 errmsg = find_time_t(&tm, 1, &t);
1271 if (errmsg)
1272 rb_raise(rb_eArgError, "%s", errmsg);
1273 return wadd(rb_time_magnify(TIMET2WV(t)), v2w(vtm->subsecx));
1276 static struct vtm *
1277 gmtimew(wideval_t timew, struct vtm *result)
1279 time_t t;
1280 struct tm tm;
1281 VALUE subsecx;
1282 wideval_t timew2;
1284 if (wlt(timew, WINT2FIXWV(0))) {
1285 gmtimew_noleapsecond(timew, result);
1286 return result;
1289 init_leap_second_info();
1291 if (number_of_leap_seconds_known == 0) {
1292 /* When init_leap_second_info() is executed, the timezone doesn't have
1293 * leap second information. Disable leap second for calculating gmtime.
1295 gmtimew_noleapsecond(timew, result);
1296 return result;
1298 else if (wlt(rb_time_magnify(TIMET2WV(known_leap_seconds_limit)), timew)) {
1299 timew = wsub(timew, rb_time_magnify(WINT2WV(number_of_leap_seconds_known)));
1300 gmtimew_noleapsecond(timew, result);
1301 return result;
1304 split_second(timew, &timew2, &subsecx);
1306 t = WV2TIMET(timew2);
1307 if (!gmtime_with_leapsecond(&t, &tm))
1308 return NULL;
1310 result->year = LONG2NUM((long)tm.tm_year + 1900);
1311 result->mon = tm.tm_mon + 1;
1312 result->mday = tm.tm_mday;
1313 result->hour = tm.tm_hour;
1314 result->min = tm.tm_min;
1315 result->sec = tm.tm_sec;
1316 result->subsecx = subsecx;
1317 result->utc_offset = INT2FIX(0);
1318 result->wday = tm.tm_wday;
1319 result->yday = tm.tm_yday+1;
1320 result->isdst = tm.tm_isdst;
1322 return result;
1325 #define GMTIMEW(w, v) \
1326 (gmtimew(w, v) ? (void)0 : rb_raise(rb_eArgError, "gmtime error"))
1328 static struct tm *localtime_with_gmtoff_zone(const time_t *t, struct tm *result, long *gmtoff, VALUE *zone);
1331 * The idea, extrapolate localtime() function, is borrowed from Perl:
1332 * http://web.archive.org/web/20080211114141/http://use.perl.org/articles/08/02/07/197204.shtml
1334 * compat_common_month_table is generated by the following program.
1335 * This table finds the last month which starts at the same day of a week.
1336 * The year 2037 is not used because:
1337 * https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=522949
1339 * #!/usr/bin/ruby
1341 * require 'date'
1343 * h = {}
1344 * 2036.downto(2010) {|y|
1345 * 1.upto(12) {|m|
1346 * next if m == 2 && y % 4 == 0
1347 * d = Date.new(y,m,1)
1348 * h[m] ||= {}
1349 * h[m][d.wday] ||= y
1353 * 1.upto(12) {|m|
1354 * print "{"
1355 * 0.upto(6) {|w|
1356 * y = h[m][w]
1357 * print " #{y},"
1359 * puts "},"
1363 static const int compat_common_month_table[12][7] = {
1364 /* Sun Mon Tue Wed Thu Fri Sat */
1365 { 2034, 2035, 2036, 2031, 2032, 2027, 2033 }, /* January */
1366 { 2026, 2027, 2033, 2034, 2035, 2030, 2031 }, /* February */
1367 { 2026, 2032, 2033, 2034, 2035, 2030, 2036 }, /* March */
1368 { 2035, 2030, 2036, 2026, 2032, 2033, 2034 }, /* April */
1369 { 2033, 2034, 2035, 2030, 2036, 2026, 2032 }, /* May */
1370 { 2036, 2026, 2032, 2033, 2034, 2035, 2030 }, /* June */
1371 { 2035, 2030, 2036, 2026, 2032, 2033, 2034 }, /* July */
1372 { 2032, 2033, 2034, 2035, 2030, 2036, 2026 }, /* August */
1373 { 2030, 2036, 2026, 2032, 2033, 2034, 2035 }, /* September */
1374 { 2034, 2035, 2030, 2036, 2026, 2032, 2033 }, /* October */
1375 { 2026, 2032, 2033, 2034, 2035, 2030, 2036 }, /* November */
1376 { 2030, 2036, 2026, 2032, 2033, 2034, 2035 }, /* December */
1380 * compat_leap_month_table is generated by following program.
1382 * #!/usr/bin/ruby
1384 * require 'date'
1386 * h = {}
1387 * 2037.downto(2010) {|y|
1388 * 1.upto(12) {|m|
1389 * next unless m == 2 && y % 4 == 0
1390 * d = Date.new(y,m,1)
1391 * h[m] ||= {}
1392 * h[m][d.wday] ||= y
1396 * 2.upto(2) {|m|
1397 * 0.upto(6) {|w|
1398 * y = h[m][w]
1399 * print " #{y},"
1401 * puts
1404 static const int compat_leap_month_table[7] = {
1405 /* Sun Mon Tue Wed Thu Fri Sat */
1406 2032, 2016, 2028, 2012, 2024, 2036, 2020, /* February */
1409 static int
1410 calc_wday(int year_mod400, int month, int day)
1412 int a, y, m;
1413 int wday;
1415 a = (14 - month) / 12;
1416 y = year_mod400 + 4800 - a;
1417 m = month + 12 * a - 3;
1418 wday = day + (153*m+2)/5 + 365*y + y/4 - y/100 + y/400 + 2;
1419 wday = wday % 7;
1420 return wday;
1423 static VALUE
1424 guess_local_offset(struct vtm *vtm_utc, int *isdst_ret, VALUE *zone_ret)
1426 struct tm tm;
1427 long gmtoff;
1428 VALUE zone;
1429 time_t t;
1430 struct vtm vtm2;
1431 VALUE timev;
1432 int year_mod400, wday;
1434 /* Daylight Saving Time was introduced in 1916.
1435 * So we don't need to care about DST before that. */
1436 if (lt(vtm_utc->year, INT2FIX(1916))) {
1437 VALUE off = INT2FIX(0);
1438 int isdst = 0;
1439 zone = rb_fstring_lit("UTC");
1441 # if defined(NEGATIVE_TIME_T)
1442 # if SIZEOF_TIME_T <= 4
1443 /* 1901-12-13 20:45:52 UTC : The oldest time in 32-bit signed time_t. */
1444 # define THE_TIME_OLD_ENOUGH ((time_t)0x80000000)
1445 # else
1446 /* Since the Royal Greenwich Observatory was commissioned in 1675,
1447 no timezone defined using GMT at 1600. */
1448 # define THE_TIME_OLD_ENOUGH ((time_t)(1600-1970)*366*24*60*60)
1449 # endif
1450 if (localtime_with_gmtoff_zone((t = THE_TIME_OLD_ENOUGH, &t), &tm, &gmtoff, &zone)) {
1451 off = LONG2FIX(gmtoff);
1452 isdst = tm.tm_isdst;
1454 else
1455 # endif
1456 /* 1970-01-01 00:00:00 UTC : The Unix epoch - the oldest time in portable time_t. */
1457 if (localtime_with_gmtoff_zone((t = 0, &t), &tm, &gmtoff, &zone)) {
1458 off = LONG2FIX(gmtoff);
1459 isdst = tm.tm_isdst;
1462 if (isdst_ret)
1463 *isdst_ret = isdst;
1464 if (zone_ret)
1465 *zone_ret = zone;
1466 return off;
1469 /* It is difficult to guess the future. */
1471 vtm2 = *vtm_utc;
1473 /* guess using a year before 2038. */
1474 year_mod400 = NUM2INT(modv(vtm_utc->year, INT2FIX(400)));
1475 wday = calc_wday(year_mod400, vtm_utc->mon, 1);
1476 if (vtm_utc->mon == 2 && leap_year_p(year_mod400))
1477 vtm2.year = INT2FIX(compat_leap_month_table[wday]);
1478 else
1479 vtm2.year = INT2FIX(compat_common_month_table[vtm_utc->mon-1][wday]);
1481 timev = w2v(rb_time_unmagnify(timegmw(&vtm2)));
1482 t = NUM2TIMET(timev);
1483 zone = str_utc;
1484 if (localtime_with_gmtoff_zone(&t, &tm, &gmtoff, &zone)) {
1485 if (isdst_ret)
1486 *isdst_ret = tm.tm_isdst;
1487 if (zone_ret)
1488 *zone_ret = zone;
1489 return LONG2FIX(gmtoff);
1493 /* Use the current time offset as a last resort. */
1494 static time_t now = 0;
1495 static long now_gmtoff = 0;
1496 static int now_isdst = 0;
1497 static VALUE now_zone;
1498 if (now == 0) {
1499 VALUE zone;
1500 now = time(NULL);
1501 localtime_with_gmtoff_zone(&now, &tm, &now_gmtoff, &zone);
1502 now_isdst = tm.tm_isdst;
1503 zone = rb_fstring(zone);
1504 rb_vm_register_global_object(zone);
1505 now_zone = zone;
1507 if (isdst_ret)
1508 *isdst_ret = now_isdst;
1509 if (zone_ret)
1510 *zone_ret = now_zone;
1511 return LONG2FIX(now_gmtoff);
1515 static VALUE
1516 small_vtm_sub(struct vtm *vtm1, struct vtm *vtm2)
1518 int off;
1520 off = vtm1->sec - vtm2->sec;
1521 off += (vtm1->min - vtm2->min) * 60;
1522 off += (vtm1->hour - vtm2->hour) * 3600;
1523 if (ne(vtm1->year, vtm2->year))
1524 off += lt(vtm1->year, vtm2->year) ? -24*3600 : 24*3600;
1525 else if (vtm1->mon != vtm2->mon)
1526 off += vtm1->mon < vtm2->mon ? -24*3600 : 24*3600;
1527 else if (vtm1->mday != vtm2->mday)
1528 off += vtm1->mday < vtm2->mday ? -24*3600 : 24*3600;
1530 return INT2FIX(off);
1533 static wideval_t
1534 timelocalw(struct vtm *vtm)
1536 time_t t;
1537 struct tm tm;
1538 VALUE v;
1539 wideval_t timew1, timew2;
1540 struct vtm vtm1, vtm2;
1541 int n;
1543 if (FIXNUM_P(vtm->year)) {
1544 long l = FIX2LONG(vtm->year) - 1900;
1545 if (l < INT_MIN || INT_MAX < l)
1546 goto no_localtime;
1547 tm.tm_year = (int)l;
1549 else {
1550 v = subv(vtm->year, INT2FIX(1900));
1551 if (lt(v, INT2NUM(INT_MIN)) || lt(INT2NUM(INT_MAX), v))
1552 goto no_localtime;
1553 tm.tm_year = NUM2INT(v);
1556 tm.tm_mon = vtm->mon-1;
1557 tm.tm_mday = vtm->mday;
1558 tm.tm_hour = vtm->hour;
1559 tm.tm_min = vtm->min;
1560 tm.tm_sec = vtm->sec;
1561 tm.tm_isdst = vtm->isdst == VTM_ISDST_INITVAL ? -1 : vtm->isdst;
1563 if (find_time_t(&tm, 0, &t))
1564 goto no_localtime;
1565 return wadd(rb_time_magnify(TIMET2WV(t)), v2w(vtm->subsecx));
1567 no_localtime:
1568 timew1 = timegmw(vtm);
1570 if (!localtimew(timew1, &vtm1))
1571 rb_raise(rb_eArgError, "localtimew error");
1573 n = vtmcmp(vtm, &vtm1);
1574 if (n == 0) {
1575 timew1 = wsub(timew1, rb_time_magnify(WINT2FIXWV(12*3600)));
1576 if (!localtimew(timew1, &vtm1))
1577 rb_raise(rb_eArgError, "localtimew error");
1578 n = 1;
1581 if (n < 0) {
1582 timew2 = timew1;
1583 vtm2 = vtm1;
1584 timew1 = wsub(timew1, rb_time_magnify(WINT2FIXWV(24*3600)));
1585 if (!localtimew(timew1, &vtm1))
1586 rb_raise(rb_eArgError, "localtimew error");
1588 else {
1589 timew2 = wadd(timew1, rb_time_magnify(WINT2FIXWV(24*3600)));
1590 if (!localtimew(timew2, &vtm2))
1591 rb_raise(rb_eArgError, "localtimew error");
1593 timew1 = wadd(timew1, rb_time_magnify(v2w(small_vtm_sub(vtm, &vtm1))));
1594 timew2 = wadd(timew2, rb_time_magnify(v2w(small_vtm_sub(vtm, &vtm2))));
1596 if (weq(timew1, timew2))
1597 return timew1;
1599 if (!localtimew(timew1, &vtm1))
1600 rb_raise(rb_eArgError, "localtimew error");
1601 if (vtm->hour != vtm1.hour || vtm->min != vtm1.min || vtm->sec != vtm1.sec)
1602 return timew2;
1604 if (!localtimew(timew2, &vtm2))
1605 rb_raise(rb_eArgError, "localtimew error");
1606 if (vtm->hour != vtm2.hour || vtm->min != vtm2.min || vtm->sec != vtm2.sec)
1607 return timew1;
1609 if (vtm->isdst)
1610 return lt(vtm1.utc_offset, vtm2.utc_offset) ? timew2 : timew1;
1611 else
1612 return lt(vtm1.utc_offset, vtm2.utc_offset) ? timew1 : timew2;
1615 static struct tm *
1616 localtime_with_gmtoff_zone(const time_t *t, struct tm *result, long *gmtoff, VALUE *zone)
1618 struct tm tm;
1620 if (LOCALTIME(t, tm)) {
1621 #if defined(HAVE_STRUCT_TM_TM_GMTOFF)
1622 *gmtoff = tm.tm_gmtoff;
1623 #else
1624 struct tm *u, *l;
1625 long off;
1626 struct tm tmbuf;
1627 l = &tm;
1628 u = GMTIME(t, tmbuf);
1629 if (!u)
1630 return NULL;
1631 if (l->tm_year != u->tm_year)
1632 off = l->tm_year < u->tm_year ? -1 : 1;
1633 else if (l->tm_mon != u->tm_mon)
1634 off = l->tm_mon < u->tm_mon ? -1 : 1;
1635 else if (l->tm_mday != u->tm_mday)
1636 off = l->tm_mday < u->tm_mday ? -1 : 1;
1637 else
1638 off = 0;
1639 off = off * 24 + l->tm_hour - u->tm_hour;
1640 off = off * 60 + l->tm_min - u->tm_min;
1641 off = off * 60 + l->tm_sec - u->tm_sec;
1642 *gmtoff = off;
1643 #endif
1645 if (zone) {
1646 #if defined(HAVE_TM_ZONE)
1647 *zone = zone_str(tm.tm_zone);
1648 #elif defined(HAVE_TZNAME) && defined(HAVE_DAYLIGHT)
1649 # if defined(RUBY_MSVCRT_VERSION) && RUBY_MSVCRT_VERSION >= 140
1650 # define tzname _tzname
1651 # define daylight _daylight
1652 # endif
1653 /* this needs tzset or localtime, instead of localtime_r */
1654 *zone = zone_str(tzname[daylight && tm.tm_isdst]);
1655 #else
1657 char buf[64];
1658 strftime(buf, sizeof(buf), "%Z", &tm);
1659 *zone = zone_str(buf);
1661 #endif
1664 *result = tm;
1665 return result;
1667 return NULL;
1670 static int
1671 timew_out_of_timet_range(wideval_t timew)
1673 VALUE timexv;
1674 #if WIDEVALUE_IS_WIDER && SIZEOF_TIME_T < SIZEOF_INT64_T
1675 if (FIXWV_P(timew)) {
1676 wideint_t t = FIXWV2WINT(timew);
1677 if (t < TIME_SCALE * (wideint_t)TIMET_MIN ||
1678 TIME_SCALE * (1 + (wideint_t)TIMET_MAX) <= t)
1679 return 1;
1680 return 0;
1682 #endif
1683 #if SIZEOF_TIME_T == SIZEOF_INT64_T
1684 if (FIXWV_P(timew)) {
1685 wideint_t t = FIXWV2WINT(timew);
1686 if (~(time_t)0 <= 0) {
1687 return 0;
1689 else {
1690 if (t < 0)
1691 return 1;
1692 return 0;
1695 #endif
1696 timexv = w2v(timew);
1697 if (lt(timexv, mulv(INT2FIX(TIME_SCALE), TIMET2NUM(TIMET_MIN))) ||
1698 le(mulv(INT2FIX(TIME_SCALE), addv(TIMET2NUM(TIMET_MAX), INT2FIX(1))), timexv))
1699 return 1;
1700 return 0;
1703 static struct vtm *
1704 localtimew(wideval_t timew, struct vtm *result)
1706 VALUE subsecx, offset;
1707 VALUE zone;
1708 int isdst;
1710 if (!timew_out_of_timet_range(timew)) {
1711 time_t t;
1712 struct tm tm;
1713 long gmtoff;
1714 wideval_t timew2;
1716 split_second(timew, &timew2, &subsecx);
1718 t = WV2TIMET(timew2);
1720 if (localtime_with_gmtoff_zone(&t, &tm, &gmtoff, &zone)) {
1721 result->year = LONG2NUM((long)tm.tm_year + 1900);
1722 result->mon = tm.tm_mon + 1;
1723 result->mday = tm.tm_mday;
1724 result->hour = tm.tm_hour;
1725 result->min = tm.tm_min;
1726 result->sec = tm.tm_sec;
1727 result->subsecx = subsecx;
1728 result->wday = tm.tm_wday;
1729 result->yday = tm.tm_yday+1;
1730 result->isdst = tm.tm_isdst;
1731 result->utc_offset = LONG2NUM(gmtoff);
1732 result->zone = zone;
1733 return result;
1737 if (!gmtimew(timew, result))
1738 return NULL;
1740 offset = guess_local_offset(result, &isdst, &zone);
1742 if (!gmtimew(wadd(timew, rb_time_magnify(v2w(offset))), result))
1743 return NULL;
1745 result->utc_offset = offset;
1746 result->isdst = isdst;
1747 result->zone = zone;
1749 return result;
1752 #define TIME_TZMODE_LOCALTIME 0
1753 #define TIME_TZMODE_UTC 1
1754 #define TIME_TZMODE_FIXOFF 2
1755 #define TIME_TZMODE_UNINITIALIZED 3
1757 struct time_object {
1758 wideval_t timew; /* time_t value * TIME_SCALE. possibly Rational. */
1759 struct vtm vtm;
1762 #define GetTimeval(obj, tobj) ((tobj) = get_timeval(obj))
1763 #define GetNewTimeval(obj, tobj) ((tobj) = get_new_timeval(obj))
1765 #define IsTimeval(obj) rb_typeddata_is_kind_of((obj), &time_data_type)
1766 #define TIME_INIT_P(tobj) ((tobj)->vtm.tzmode != TIME_TZMODE_UNINITIALIZED)
1768 #define TZMODE_UTC_P(tobj) ((tobj)->vtm.tzmode == TIME_TZMODE_UTC)
1769 #define TZMODE_SET_UTC(tobj) ((tobj)->vtm.tzmode = TIME_TZMODE_UTC)
1771 #define TZMODE_LOCALTIME_P(tobj) ((tobj)->vtm.tzmode == TIME_TZMODE_LOCALTIME)
1772 #define TZMODE_SET_LOCALTIME(tobj) ((tobj)->vtm.tzmode = TIME_TZMODE_LOCALTIME)
1774 #define TZMODE_FIXOFF_P(tobj) ((tobj)->vtm.tzmode == TIME_TZMODE_FIXOFF)
1775 #define TZMODE_SET_FIXOFF(time, tobj, off) do { \
1776 (tobj)->vtm.tzmode = TIME_TZMODE_FIXOFF; \
1777 RB_OBJ_WRITE_UNALIGNED(time, &(tobj)->vtm.utc_offset, off); \
1778 } while (0)
1780 #define TZMODE_COPY(tobj1, tobj2) \
1781 ((tobj1)->vtm.tzmode = (tobj2)->vtm.tzmode, \
1782 (tobj1)->vtm.utc_offset = (tobj2)->vtm.utc_offset, \
1783 (tobj1)->vtm.zone = (tobj2)->vtm.zone)
1785 static int zone_localtime(VALUE zone, VALUE time);
1786 static VALUE time_get_tm(VALUE, struct time_object *);
1787 #define MAKE_TM(time, tobj) \
1788 do { \
1789 if ((tobj)->vtm.tm_got == 0) { \
1790 time_get_tm((time), (tobj)); \
1792 } while (0)
1793 #define MAKE_TM_ENSURE(time, tobj, cond) \
1794 do { \
1795 MAKE_TM(time, tobj); \
1796 if (!(cond)) { \
1797 force_make_tm(time, tobj); \
1799 } while (0)
1801 static void
1802 time_set_timew(VALUE time, struct time_object *tobj, wideval_t timew)
1804 tobj->timew = timew;
1805 if (!FIXWV_P(timew)) {
1806 RB_OBJ_WRITTEN(time, Qnil, w2v(timew));
1810 static void
1811 time_set_vtm(VALUE time, struct time_object *tobj, struct vtm vtm)
1813 tobj->vtm = vtm;
1815 RB_OBJ_WRITTEN(time, Qnil, tobj->vtm.year);
1816 RB_OBJ_WRITTEN(time, Qnil, tobj->vtm.subsecx);
1817 RB_OBJ_WRITTEN(time, Qnil, tobj->vtm.utc_offset);
1818 RB_OBJ_WRITTEN(time, Qnil, tobj->vtm.zone);
1821 static inline void
1822 force_make_tm(VALUE time, struct time_object *tobj)
1824 VALUE zone = tobj->vtm.zone;
1825 if (!NIL_P(zone) && zone != str_empty && zone != str_utc) {
1826 if (zone_localtime(zone, time)) return;
1828 tobj->vtm.tm_got = 0;
1829 time_get_tm(time, tobj);
1832 static void
1833 time_mark(void *ptr)
1835 struct time_object *tobj = ptr;
1836 if (!FIXWV_P(tobj->timew))
1837 rb_gc_mark(w2v(tobj->timew));
1838 rb_gc_mark(tobj->vtm.year);
1839 rb_gc_mark(tobj->vtm.subsecx);
1840 rb_gc_mark(tobj->vtm.utc_offset);
1841 rb_gc_mark(tobj->vtm.zone);
1844 static const rb_data_type_t time_data_type = {
1845 "time",
1847 time_mark,
1848 RUBY_TYPED_DEFAULT_FREE,
1849 NULL, // No external memory to report,
1851 0, 0,
1852 (RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE),
1855 static VALUE
1856 time_s_alloc(VALUE klass)
1858 VALUE obj;
1859 struct time_object *tobj;
1861 obj = TypedData_Make_Struct(klass, struct time_object, &time_data_type, tobj);
1862 tobj->vtm.tzmode = TIME_TZMODE_UNINITIALIZED;
1863 tobj->vtm.tm_got = 0;
1864 time_set_timew(obj, tobj, WINT2FIXWV(0));
1865 tobj->vtm.zone = Qnil;
1867 return obj;
1870 static struct time_object *
1871 get_timeval(VALUE obj)
1873 struct time_object *tobj;
1874 TypedData_Get_Struct(obj, struct time_object, &time_data_type, tobj);
1875 if (!TIME_INIT_P(tobj)) {
1876 rb_raise(rb_eTypeError, "uninitialized %"PRIsVALUE, rb_obj_class(obj));
1878 return tobj;
1881 static struct time_object *
1882 get_new_timeval(VALUE obj)
1884 struct time_object *tobj;
1885 TypedData_Get_Struct(obj, struct time_object, &time_data_type, tobj);
1886 if (TIME_INIT_P(tobj)) {
1887 rb_raise(rb_eTypeError, "already initialized %"PRIsVALUE, rb_obj_class(obj));
1889 return tobj;
1892 static void
1893 time_modify(VALUE time)
1895 rb_check_frozen(time);
1898 static wideval_t
1899 timenano2timew(time_t sec, long nsec)
1901 wideval_t timew;
1903 timew = rb_time_magnify(TIMET2WV(sec));
1904 if (nsec)
1905 timew = wadd(timew, wmulquoll(WINT2WV(nsec), TIME_SCALE, 1000000000));
1906 return timew;
1909 static struct timespec
1910 timew2timespec(wideval_t timew)
1912 VALUE subsecx;
1913 struct timespec ts;
1914 wideval_t timew2;
1916 if (timew_out_of_timet_range(timew))
1917 rb_raise(rb_eArgError, "time out of system range");
1918 split_second(timew, &timew2, &subsecx);
1919 ts.tv_sec = WV2TIMET(timew2);
1920 ts.tv_nsec = NUM2LONG(mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE)));
1921 return ts;
1924 static struct timespec *
1925 timew2timespec_exact(wideval_t timew, struct timespec *ts)
1927 VALUE subsecx;
1928 wideval_t timew2;
1929 VALUE nsecv;
1931 if (timew_out_of_timet_range(timew))
1932 return NULL;
1933 split_second(timew, &timew2, &subsecx);
1934 ts->tv_sec = WV2TIMET(timew2);
1935 nsecv = mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE));
1936 if (!FIXNUM_P(nsecv))
1937 return NULL;
1938 ts->tv_nsec = NUM2LONG(nsecv);
1939 return ts;
1942 void
1943 rb_timespec_now(struct timespec *ts)
1945 #ifdef HAVE_CLOCK_GETTIME
1946 if (clock_gettime(CLOCK_REALTIME, ts) == -1) {
1947 rb_sys_fail("clock_gettime");
1949 #else
1951 struct timeval tv;
1952 if (gettimeofday(&tv, 0) < 0) {
1953 rb_sys_fail("gettimeofday");
1955 ts->tv_sec = tv.tv_sec;
1956 ts->tv_nsec = tv.tv_usec * 1000;
1958 #endif
1962 * Sets the current time information into _time_.
1963 * Returns _time_.
1965 static VALUE
1966 time_init_now(rb_execution_context_t *ec, VALUE time, VALUE zone)
1968 struct time_object *tobj;
1969 struct timespec ts;
1971 time_modify(time);
1972 GetNewTimeval(time, tobj);
1973 TZMODE_SET_LOCALTIME(tobj);
1974 tobj->vtm.tm_got=0;
1975 rb_timespec_now(&ts);
1976 time_set_timew(time, tobj, timenano2timew(ts.tv_sec, ts.tv_nsec));
1978 if (!NIL_P(zone)) {
1979 time_zonelocal(time, zone);
1981 return time;
1984 static VALUE
1985 time_s_now(rb_execution_context_t *ec, VALUE klass, VALUE zone)
1987 VALUE t = time_s_alloc(klass);
1988 return time_init_now(ec, t, zone);
1991 static VALUE
1992 time_set_utc_offset(VALUE time, VALUE off)
1994 struct time_object *tobj;
1995 off = num_exact(off);
1997 time_modify(time);
1998 GetTimeval(time, tobj);
2000 tobj->vtm.tm_got = 0;
2001 tobj->vtm.zone = Qnil;
2002 TZMODE_SET_FIXOFF(time, tobj, off);
2004 return time;
2007 static void
2008 vtm_add_offset(struct vtm *vtm, VALUE off, int sign)
2010 VALUE subsec, v;
2011 int sec, min, hour;
2012 int day;
2014 if (lt(off, INT2FIX(0))) {
2015 sign = -sign;
2016 off = neg(off);
2018 divmodv(off, INT2FIX(1), &off, &subsec);
2019 divmodv(off, INT2FIX(60), &off, &v);
2020 sec = NUM2INT(v);
2021 divmodv(off, INT2FIX(60), &off, &v);
2022 min = NUM2INT(v);
2023 divmodv(off, INT2FIX(24), &off, &v);
2024 hour = NUM2INT(v);
2026 if (sign < 0) {
2027 subsec = neg(subsec);
2028 sec = -sec;
2029 min = -min;
2030 hour = -hour;
2033 day = 0;
2035 if (!rb_equal(subsec, INT2FIX(0))) {
2036 vtm->subsecx = addv(vtm->subsecx, w2v(rb_time_magnify(v2w(subsec))));
2037 if (lt(vtm->subsecx, INT2FIX(0))) {
2038 vtm->subsecx = addv(vtm->subsecx, INT2FIX(TIME_SCALE));
2039 sec -= 1;
2041 if (le(INT2FIX(TIME_SCALE), vtm->subsecx)) {
2042 vtm->subsecx = subv(vtm->subsecx, INT2FIX(TIME_SCALE));
2043 sec += 1;
2046 if (sec) {
2047 /* If sec + subsec == 0, don't change vtm->sec.
2048 * It may be 60 which is a leap second. */
2049 sec += vtm->sec;
2050 if (sec < 0) {
2051 sec += 60;
2052 min -= 1;
2054 if (60 <= sec) {
2055 sec -= 60;
2056 min += 1;
2058 vtm->sec = sec;
2060 if (min) {
2061 min += vtm->min;
2062 if (min < 0) {
2063 min += 60;
2064 hour -= 1;
2066 if (60 <= min) {
2067 min -= 60;
2068 hour += 1;
2070 vtm->min = min;
2072 if (hour) {
2073 hour += vtm->hour;
2074 if (hour < 0) {
2075 hour += 24;
2076 day = -1;
2078 if (24 <= hour) {
2079 hour -= 24;
2080 day = 1;
2082 vtm->hour = hour;
2085 vtm_add_day(vtm, day);
2088 static void
2089 vtm_add_day(struct vtm *vtm, int day)
2091 if (day) {
2092 if (day < 0) {
2093 if (vtm->mon == 1 && vtm->mday == 1) {
2094 vtm->mday = 31;
2095 vtm->mon = 12; /* December */
2096 vtm->year = subv(vtm->year, INT2FIX(1));
2097 if (vtm->yday != 0)
2098 vtm->yday = leap_year_v_p(vtm->year) ? 366 : 365;
2100 else if (vtm->mday == 1) {
2101 const int8_t *days_in_month = days_in_month_in_v(vtm->year);
2102 vtm->mon--;
2103 vtm->mday = days_in_month[vtm->mon-1];
2104 if (vtm->yday != 0) vtm->yday--;
2106 else {
2107 vtm->mday--;
2108 if (vtm->yday != 0) vtm->yday--;
2110 if (vtm->wday != VTM_WDAY_INITVAL) vtm->wday = (vtm->wday + 6) % 7;
2112 else {
2113 int leap = leap_year_v_p(vtm->year);
2114 if (vtm->mon == 12 && vtm->mday == 31) {
2115 vtm->year = addv(vtm->year, INT2FIX(1));
2116 vtm->mon = 1; /* January */
2117 vtm->mday = 1;
2118 vtm->yday = 1;
2120 else if (vtm->mday == days_in_month_of(leap)[vtm->mon-1]) {
2121 vtm->mon++;
2122 vtm->mday = 1;
2123 if (vtm->yday != 0) vtm->yday++;
2125 else {
2126 vtm->mday++;
2127 if (vtm->yday != 0) vtm->yday++;
2129 if (vtm->wday != VTM_WDAY_INITVAL) vtm->wday = (vtm->wday + 1) % 7;
2134 static int
2135 maybe_tzobj_p(VALUE obj)
2137 if (NIL_P(obj)) return FALSE;
2138 if (RB_INTEGER_TYPE_P(obj)) return FALSE;
2139 if (RB_TYPE_P(obj, T_STRING)) return FALSE;
2140 return TRUE;
2143 NORETURN(static void invalid_utc_offset(VALUE));
2144 static void
2145 invalid_utc_offset(VALUE zone)
2147 rb_raise(rb_eArgError, "\"+HH:MM\", \"-HH:MM\", \"UTC\" or "
2148 "\"A\"..\"I\",\"K\"..\"Z\" expected for utc_offset: %"PRIsVALUE,
2149 zone);
2152 static VALUE
2153 utc_offset_arg(VALUE arg)
2155 VALUE tmp;
2156 if (!NIL_P(tmp = rb_check_string_type(arg))) {
2157 int n = 0;
2158 const char *s = RSTRING_PTR(tmp), *min = NULL, *sec = NULL;
2159 if (!rb_enc_str_asciicompat_p(tmp)) {
2160 goto invalid_utc_offset;
2162 switch (RSTRING_LEN(tmp)) {
2163 case 1:
2164 if (s[0] == 'Z') {
2165 return UTC_ZONE;
2167 /* Military Time Zone Names */
2168 if (s[0] >= 'A' && s[0] <= 'I') {
2169 n = (int)s[0] - 'A' + 1;
2171 /* No 'J' zone */
2172 else if (s[0] >= 'K' && s[0] <= 'M') {
2173 n = (int)s[0] - 'A';
2175 else if (s[0] >= 'N' && s[0] <= 'Y') {
2176 n = 'M' - (int)s[0];
2178 else {
2179 goto invalid_utc_offset;
2181 n *= 3600;
2182 return INT2FIX(n);
2183 case 3:
2184 if (STRNCASECMP("UTC", s, 3) == 0) {
2185 return UTC_ZONE;
2187 break; /* +HH */
2188 case 7: /* +HHMMSS */
2189 sec = s+5;
2190 /* fallthrough */
2191 case 5: /* +HHMM */
2192 min = s+3;
2193 break;
2194 case 9: /* +HH:MM:SS */
2195 if (s[6] != ':') goto invalid_utc_offset;
2196 sec = s+7;
2197 /* fallthrough */
2198 case 6: /* +HH:MM */
2199 if (s[3] != ':') goto invalid_utc_offset;
2200 min = s+4;
2201 break;
2202 default:
2203 goto invalid_utc_offset;
2205 if (sec) {
2206 if (!ISDIGIT(sec[0]) || !ISDIGIT(sec[1])) goto invalid_utc_offset;
2207 n += (sec[0] * 10 + sec[1] - '0' * 11);
2208 ASSUME(min);
2210 if (min) {
2211 if (!ISDIGIT(min[0]) || !ISDIGIT(min[1])) goto invalid_utc_offset;
2212 if (min[0] > '5') goto invalid_utc_offset;
2213 n += (min[0] * 10 + min[1] - '0' * 11) * 60;
2215 if (s[0] != '+' && s[0] != '-') goto invalid_utc_offset;
2216 if (!ISDIGIT(s[1]) || !ISDIGIT(s[2])) goto invalid_utc_offset;
2217 n += (s[1] * 10 + s[2] - '0' * 11) * 3600;
2218 if (s[0] == '-') {
2219 if (n == 0) return UTC_ZONE;
2220 n = -n;
2222 return INT2FIX(n);
2224 else {
2225 return num_exact(arg);
2227 invalid_utc_offset:
2228 return Qnil;
2231 static void
2232 zone_set_offset(VALUE zone, struct time_object *tobj,
2233 wideval_t tlocal, wideval_t tutc)
2235 /* tlocal and tutc must be unmagnified and in seconds */
2236 wideval_t w = wsub(tlocal, tutc);
2237 VALUE off = w2v(w);
2238 validate_utc_offset(off);
2239 tobj->vtm.utc_offset = off;
2240 tobj->vtm.zone = zone;
2241 TZMODE_SET_LOCALTIME(tobj);
2244 static wideval_t
2245 extract_time(VALUE time)
2247 wideval_t t;
2248 const ID id_to_i = idTo_i;
2250 #define EXTRACT_TIME() do { \
2251 t = v2w(rb_Integer(AREF(to_i))); \
2252 } while (0)
2254 if (rb_typeddata_is_kind_of(time, &time_data_type)) {
2255 struct time_object *tobj = RTYPEDDATA_GET_DATA(time);
2257 time_gmtime(time); /* ensure tm got */
2258 t = rb_time_unmagnify(tobj->timew);
2260 RB_GC_GUARD(time);
2262 else if (RB_TYPE_P(time, T_STRUCT)) {
2263 #define AREF(x) rb_struct_aref(time, ID2SYM(id_##x))
2264 EXTRACT_TIME();
2265 #undef AREF
2267 else {
2268 #define AREF(x) rb_funcallv(time, id_##x, 0, 0)
2269 EXTRACT_TIME();
2270 #undef AREF
2272 #undef EXTRACT_TIME
2274 return t;
2277 static wideval_t
2278 extract_vtm(VALUE time, VALUE orig_time, struct time_object *orig_tobj, VALUE subsecx)
2280 wideval_t t;
2281 const ID id_to_i = idTo_i;
2282 struct vtm *vtm = &orig_tobj->vtm;
2284 #define EXTRACT_VTM() do { \
2285 VALUE subsecx; \
2286 vtm->year = obj2vint(AREF(year)); \
2287 vtm->mon = month_arg(AREF(mon)); \
2288 vtm->mday = obj2ubits(AREF(mday), 5); \
2289 vtm->hour = obj2ubits(AREF(hour), 5); \
2290 vtm->min = obj2ubits(AREF(min), 6); \
2291 vtm->sec = obj2subsecx(AREF(sec), &subsecx); \
2292 vtm->isdst = RTEST(AREF(isdst)); \
2293 vtm->utc_offset = Qnil; \
2294 t = v2w(rb_Integer(AREF(to_i))); \
2295 } while (0)
2297 if (rb_typeddata_is_kind_of(time, &time_data_type)) {
2298 struct time_object *tobj = RTYPEDDATA_GET_DATA(time);
2300 time_get_tm(time, tobj);
2301 time_set_vtm(orig_time, orig_tobj, tobj->vtm);
2302 t = rb_time_unmagnify(tobj->timew);
2303 if (TZMODE_FIXOFF_P(tobj) && vtm->utc_offset != INT2FIX(0))
2304 t = wadd(t, v2w(vtm->utc_offset));
2306 RB_GC_GUARD(time);
2308 else if (RB_TYPE_P(time, T_STRUCT)) {
2309 #define AREF(x) rb_struct_aref(time, ID2SYM(id_##x))
2310 EXTRACT_VTM();
2311 #undef AREF
2313 else if (rb_integer_type_p(time)) {
2314 t = v2w(time);
2315 struct vtm temp_vtm = *vtm;
2316 GMTIMEW(rb_time_magnify(t), &temp_vtm);
2317 time_set_vtm(orig_time, orig_tobj, temp_vtm);
2319 else {
2320 #define AREF(x) rb_funcallv(time, id_##x, 0, 0)
2321 EXTRACT_VTM();
2322 #undef AREF
2324 #undef EXTRACT_VTM
2326 RB_OBJ_WRITE_UNALIGNED(orig_time, &vtm->subsecx, subsecx);
2328 validate_vtm(vtm);
2329 return t;
2332 static void
2333 zone_set_dst(VALUE zone, struct time_object *tobj, VALUE tm)
2335 ID id_dst_p;
2336 VALUE dst;
2337 CONST_ID(id_dst_p, "dst?");
2338 dst = rb_check_funcall(zone, id_dst_p, 1, &tm);
2339 tobj->vtm.isdst = (!UNDEF_P(dst) && RTEST(dst));
2342 static int
2343 zone_timelocal(VALUE zone, VALUE time)
2345 VALUE utc, tm;
2346 struct time_object *tobj = RTYPEDDATA_GET_DATA(time);
2347 wideval_t t, s;
2349 wdivmod(tobj->timew, WINT2FIXWV(TIME_SCALE), &t, &s);
2350 tm = tm_from_time(rb_cTimeTM, time);
2351 utc = rb_check_funcall(zone, id_local_to_utc, 1, &tm);
2352 if (UNDEF_P(utc)) return 0;
2354 s = extract_time(utc);
2355 zone_set_offset(zone, tobj, t, s);
2356 s = rb_time_magnify(s);
2357 if (tobj->vtm.subsecx != INT2FIX(0)) {
2358 s = wadd(s, v2w(tobj->vtm.subsecx));
2360 time_set_timew(time, tobj, s);
2362 zone_set_dst(zone, tobj, tm);
2364 RB_GC_GUARD(time);
2366 return 1;
2369 static int
2370 zone_localtime(VALUE zone, VALUE time)
2372 VALUE local, tm, subsecx;
2373 struct time_object *tobj = RTYPEDDATA_GET_DATA(time);
2374 wideval_t t, s;
2376 split_second(tobj->timew, &t, &subsecx);
2377 tm = tm_from_time(rb_cTimeTM, time);
2379 local = rb_check_funcall(zone, id_utc_to_local, 1, &tm);
2380 if (UNDEF_P(local)) return 0;
2382 s = extract_vtm(local, time, tobj, subsecx);
2383 tobj->vtm.tm_got = 1;
2384 zone_set_offset(zone, tobj, s, t);
2385 zone_set_dst(zone, tobj, tm);
2387 RB_GC_GUARD(time);
2389 return 1;
2392 static VALUE
2393 find_timezone(VALUE time, VALUE zone)
2395 VALUE klass = CLASS_OF(time);
2397 return rb_check_funcall_default(klass, id_find_timezone, 1, &zone, Qnil);
2400 /* Turn the special case 24:00:00 of already validated vtm into
2401 * 00:00:00 the next day */
2402 static void
2403 vtm_day_wraparound(struct vtm *vtm)
2405 if (vtm->hour < 24) return;
2407 /* Assuming UTC and no care of DST, just reset hour and advance
2408 * date, not to discard the validated vtm. */
2409 vtm->hour = 0;
2410 vtm_add_day(vtm, 1);
2413 static VALUE time_init_vtm(VALUE time, struct vtm vtm, VALUE zone);
2416 * Sets the broken-out time information into _time_.
2417 * Returns _time_.
2419 static VALUE
2420 time_init_args(rb_execution_context_t *ec, VALUE time, VALUE year, VALUE mon, VALUE mday,
2421 VALUE hour, VALUE min, VALUE sec, VALUE zone)
2423 struct vtm vtm;
2425 vtm.wday = VTM_WDAY_INITVAL;
2426 vtm.yday = 0;
2427 vtm.zone = str_empty;
2429 vtm.year = obj2vint(year);
2431 vtm.mon = NIL_P(mon) ? 1 : month_arg(mon);
2433 vtm.mday = NIL_P(mday) ? 1 : obj2ubits(mday, 5);
2435 vtm.hour = NIL_P(hour) ? 0 : obj2ubits(hour, 5);
2437 vtm.min = NIL_P(min) ? 0 : obj2ubits(min, 6);
2439 if (NIL_P(sec)) {
2440 vtm.sec = 0;
2441 vtm.subsecx = INT2FIX(0);
2443 else {
2444 VALUE subsecx;
2445 vtm.sec = obj2subsecx(sec, &subsecx);
2446 vtm.subsecx = subsecx;
2449 return time_init_vtm(time, vtm, zone);
2452 static VALUE
2453 time_init_vtm(VALUE time, struct vtm vtm, VALUE zone)
2455 VALUE utc = Qnil;
2456 struct time_object *tobj;
2458 vtm.isdst = VTM_ISDST_INITVAL;
2459 vtm.utc_offset = Qnil;
2460 const VALUE arg = zone;
2461 if (!NIL_P(arg)) {
2462 zone = Qnil;
2463 if (arg == ID2SYM(rb_intern("dst")))
2464 vtm.isdst = 1;
2465 else if (arg == ID2SYM(rb_intern("std")))
2466 vtm.isdst = 0;
2467 else if (maybe_tzobj_p(arg))
2468 zone = arg;
2469 else if (!NIL_P(utc = utc_offset_arg(arg)))
2470 vtm.utc_offset = utc == UTC_ZONE ? INT2FIX(0) : utc;
2471 else if (NIL_P(zone = find_timezone(time, arg)))
2472 invalid_utc_offset(arg);
2475 validate_vtm(&vtm);
2477 time_modify(time);
2478 GetNewTimeval(time, tobj);
2480 if (!NIL_P(zone)) {
2481 time_set_timew(time, tobj, timegmw(&vtm));
2482 vtm_day_wraparound(&vtm);
2483 time_set_vtm(time, tobj, vtm);
2484 tobj->vtm.tm_got = 1;
2485 TZMODE_SET_LOCALTIME(tobj);
2486 if (zone_timelocal(zone, time)) {
2487 return time;
2489 else if (NIL_P(vtm.utc_offset = utc_offset_arg(zone))) {
2490 if (NIL_P(zone = find_timezone(time, zone)) || !zone_timelocal(zone, time))
2491 invalid_utc_offset(arg);
2495 if (utc == UTC_ZONE) {
2496 time_set_timew(time, tobj, timegmw(&vtm));
2497 vtm.isdst = 0; /* No DST in UTC */
2498 vtm_day_wraparound(&vtm);
2499 time_set_vtm(time, tobj, vtm);
2500 tobj->vtm.tm_got = 1;
2501 TZMODE_SET_UTC(tobj);
2502 return time;
2505 TZMODE_SET_LOCALTIME(tobj);
2506 tobj->vtm.tm_got=0;
2508 if (!NIL_P(vtm.utc_offset)) {
2509 VALUE off = vtm.utc_offset;
2510 vtm_add_offset(&vtm, off, -1);
2511 vtm.utc_offset = Qnil;
2512 time_set_timew(time, tobj, timegmw(&vtm));
2514 return time_set_utc_offset(time, off);
2516 else {
2517 time_set_timew(time, tobj, timelocalw(&vtm));
2519 return time_localtime(time);
2523 static int
2524 two_digits(const char *ptr, const char *end, const char **endp, const char *name)
2526 ssize_t len = end - ptr;
2527 if (len < 2 || (!ISDIGIT(ptr[0]) || !ISDIGIT(ptr[1])) ||
2528 ((len > 2) && ISDIGIT(ptr[2]))) {
2529 VALUE mesg = rb_sprintf("two digits %s is expected", name);
2530 if (ptr[-1] == '-' || ptr[-1] == ':') {
2531 rb_str_catf(mesg, " after '%c'", ptr[-1]);
2533 rb_str_catf(mesg, ": %.*s", ((len > 10) ? 10 : (int)(end - ptr)) + 1, ptr - 1);
2534 rb_exc_raise(rb_exc_new_str(rb_eArgError, mesg));
2536 *endp = ptr + 2;
2537 return (ptr[0] - '0') * 10 + (ptr[1] - '0');
2540 static VALUE
2541 parse_int(const char *ptr, const char *end, const char **endp, size_t *ndigits, bool sign)
2543 ssize_t len = (end - ptr);
2544 int flags = sign ? RB_INT_PARSE_SIGN : 0;
2545 return rb_int_parse_cstr(ptr, len, (char **)endp, ndigits, 10, flags);
2549 * Parses _str_ and sets the broken-out time information into _time_.
2550 * If _str_ is not a String, returns +nil+, otherwise returns _time_.
2552 static VALUE
2553 time_init_parse(rb_execution_context_t *ec, VALUE time, VALUE str, VALUE zone, VALUE precision)
2555 if (NIL_P(str = rb_check_string_type(str))) return Qnil;
2556 if (!rb_enc_str_asciicompat_p(str)) {
2557 rb_raise(rb_eArgError, "time string should have ASCII compatible encoding");
2560 const char *const begin = RSTRING_PTR(str);
2561 const char *const end = RSTRING_END(str);
2562 const char *ptr = begin;
2563 VALUE year = Qnil, subsec = Qnil;
2564 int mon = -1, mday = -1, hour = -1, min = -1, sec = -1;
2565 size_t ndigits;
2566 size_t prec = NIL_P(precision) ? SIZE_MAX : NUM2SIZET(precision);
2568 if ((ptr < end) && (ISSPACE(*ptr) || ISSPACE(*(end-1)))) {
2569 rb_raise(rb_eArgError, "can't parse: %+"PRIsVALUE, str);
2571 year = parse_int(ptr, end, &ptr, &ndigits, true);
2572 if (NIL_P(year)) {
2573 rb_raise(rb_eArgError, "can't parse: %+"PRIsVALUE, str);
2575 else if (ndigits < 4) {
2576 rb_raise(rb_eArgError, "year must be 4 or more digits: %.*s", (int)ndigits, ptr - ndigits);
2578 else if (ptr == end) {
2579 goto only_year;
2581 do {
2582 #define peekable_p(n) ((ptrdiff_t)(n) < (end - ptr))
2583 #define peek_n(c, n) (peekable_p(n) && ((unsigned char)ptr[n] == (c)))
2584 #define peek(c) peek_n(c, 0)
2585 #define peekc_n(n) (peekable_p(n) ? (int)(unsigned char)ptr[n] : -1)
2586 #define peekc() peekc_n(0)
2587 #define expect_two_digits(x, bits) \
2588 (((unsigned int)(x = two_digits(ptr + 1, end, &ptr, #x)) > (1U << bits) - 1) ? \
2589 rb_raise(rb_eArgError, #x" out of range") : (void)0)
2590 if (!peek('-')) break;
2591 expect_two_digits(mon, 4);
2592 if (!peek('-')) break;
2593 expect_two_digits(mday, 5);
2594 if (!peek(' ') && !peek('T')) break;
2595 const char *const time_part = ptr + 1;
2596 if (!ISDIGIT(peekc_n(1))) break;
2597 #define nofraction(x) \
2598 if (peek('.')) { \
2599 rb_raise(rb_eArgError, "fraction " #x " is not supported: %.*s", \
2600 (int)(ptr + 1 - time_part), time_part); \
2602 #define need_colon(x) \
2603 if (!peek(':')) { \
2604 rb_raise(rb_eArgError, "missing " #x " part: %.*s", \
2605 (int)(ptr + 1 - time_part), time_part); \
2607 expect_two_digits(hour, 5);
2608 nofraction(hour);
2609 need_colon(min);
2610 expect_two_digits(min, 6);
2611 nofraction(min);
2612 need_colon(sec);
2613 expect_two_digits(sec, 6);
2614 if (peek('.')) {
2615 ptr++;
2616 for (ndigits = 0; ndigits < prec && ISDIGIT(peekc_n(ndigits)); ++ndigits);
2617 if (!ndigits) {
2618 int clen = rb_enc_precise_mbclen(ptr, end, rb_enc_get(str));
2619 if (clen < 0) clen = 0;
2620 rb_raise(rb_eArgError, "subsecond expected after dot: %.*s",
2621 (int)(ptr - time_part) + clen, time_part);
2623 subsec = parse_int(ptr, ptr + ndigits, &ptr, &ndigits, false);
2624 if (NIL_P(subsec)) break;
2625 while (ptr < end && ISDIGIT(*ptr)) ptr++;
2627 } while (0);
2628 while (ptr < end && ISSPACE(*ptr)) ptr++;
2629 const char *const zstr = ptr;
2630 while (ptr < end && !ISSPACE(*ptr)) ptr++;
2631 const char *const zend = ptr;
2632 while (ptr < end && ISSPACE(*ptr)) ptr++;
2633 if (ptr < end) {
2634 VALUE mesg = rb_str_new_cstr("can't parse at: ");
2635 rb_str_cat(mesg, ptr, end - ptr);
2636 rb_exc_raise(rb_exc_new_str(rb_eArgError, mesg));
2638 if (zend > zstr) {
2639 zone = rb_str_subseq(str, zstr - begin, zend - zstr);
2641 else if (hour == -1) {
2642 rb_raise(rb_eArgError, "no time information");
2644 if (!NIL_P(subsec)) {
2645 /* subseconds is the last using ndigits */
2646 static const size_t TIME_SCALE_NUMDIGITS =
2647 /* TIME_SCALE should be 10000... */
2648 rb_strlen_lit(STRINGIZE(TIME_SCALE)) - 1;
2650 if (ndigits < TIME_SCALE_NUMDIGITS) {
2651 VALUE mul = rb_int_positive_pow(10, TIME_SCALE_NUMDIGITS - ndigits);
2652 subsec = rb_int_mul(subsec, mul);
2654 else if (ndigits > TIME_SCALE_NUMDIGITS) {
2655 VALUE num = rb_int_positive_pow(10, ndigits - TIME_SCALE_NUMDIGITS);
2656 subsec = rb_rational_new(subsec, num);
2660 only_year:
2663 struct vtm vtm = {
2664 .wday = VTM_WDAY_INITVAL,
2665 .yday = 0,
2666 .zone = str_empty,
2667 .year = year,
2668 .mon = (mon < 0) ? 1 : mon,
2669 .mday = (mday < 0) ? 1 : mday,
2670 .hour = (hour < 0) ? 0 : hour,
2671 .min = (min < 0) ? 0 : min,
2672 .sec = (sec < 0) ? 0 : sec,
2673 .subsecx = NIL_P(subsec) ? INT2FIX(0) : subsec,
2675 return time_init_vtm(time, vtm, zone);
2678 static void
2679 subsec_normalize(time_t *secp, long *subsecp, const long maxsubsec)
2681 time_t sec = *secp;
2682 long subsec = *subsecp;
2683 long sec2;
2685 if (UNLIKELY(subsec >= maxsubsec)) { /* subsec positive overflow */
2686 sec2 = subsec / maxsubsec;
2687 if (TIMET_MAX - sec2 < sec) {
2688 rb_raise(rb_eRangeError, "out of Time range");
2690 subsec -= sec2 * maxsubsec;
2691 sec += sec2;
2693 else if (UNLIKELY(subsec < 0)) { /* subsec negative overflow */
2694 sec2 = NDIV(subsec, maxsubsec); /* negative div */
2695 if (sec < TIMET_MIN - sec2) {
2696 rb_raise(rb_eRangeError, "out of Time range");
2698 subsec -= sec2 * maxsubsec;
2699 sec += sec2;
2701 #ifndef NEGATIVE_TIME_T
2702 if (sec < 0)
2703 rb_raise(rb_eArgError, "time must be positive");
2704 #endif
2705 *secp = sec;
2706 *subsecp = subsec;
2709 #define time_usec_normalize(secp, usecp) subsec_normalize(secp, usecp, 1000000)
2710 #define time_nsec_normalize(secp, nsecp) subsec_normalize(secp, nsecp, 1000000000)
2712 static wideval_t
2713 nsec2timew(time_t sec, long nsec)
2715 time_nsec_normalize(&sec, &nsec);
2716 return timenano2timew(sec, nsec);
2719 static VALUE
2720 time_new_timew(VALUE klass, wideval_t timew)
2722 VALUE time = time_s_alloc(klass);
2723 struct time_object *tobj;
2725 tobj = RTYPEDDATA_GET_DATA(time); /* skip type check */
2726 TZMODE_SET_LOCALTIME(tobj);
2727 time_set_timew(time, tobj, timew);
2729 return time;
2732 VALUE
2733 rb_time_new(time_t sec, long usec)
2735 time_usec_normalize(&sec, &usec);
2736 return time_new_timew(rb_cTime, timenano2timew(sec, usec * 1000));
2739 /* returns localtime time object */
2740 VALUE
2741 rb_time_nano_new(time_t sec, long nsec)
2743 return time_new_timew(rb_cTime, nsec2timew(sec, nsec));
2746 VALUE
2747 rb_time_timespec_new(const struct timespec *ts, int offset)
2749 struct time_object *tobj;
2750 VALUE time = time_new_timew(rb_cTime, nsec2timew(ts->tv_sec, ts->tv_nsec));
2752 if (-86400 < offset && offset < 86400) { /* fixoff */
2753 GetTimeval(time, tobj);
2754 TZMODE_SET_FIXOFF(time, tobj, INT2FIX(offset));
2756 else if (offset == INT_MAX) { /* localtime */
2758 else if (offset == INT_MAX-1) { /* UTC */
2759 GetTimeval(time, tobj);
2760 TZMODE_SET_UTC(tobj);
2762 else {
2763 rb_raise(rb_eArgError, "utc_offset out of range");
2766 return time;
2769 VALUE
2770 rb_time_num_new(VALUE timev, VALUE off)
2772 VALUE time = time_new_timew(rb_cTime, rb_time_magnify(v2w(timev)));
2774 if (!NIL_P(off)) {
2775 VALUE zone = off;
2777 if (maybe_tzobj_p(zone)) {
2778 time_gmtime(time);
2779 if (zone_timelocal(zone, time)) return time;
2781 if (NIL_P(off = utc_offset_arg(off))) {
2782 off = zone;
2783 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
2784 time_gmtime(time);
2785 if (!zone_timelocal(zone, time)) invalid_utc_offset(off);
2786 return time;
2788 else if (off == UTC_ZONE) {
2789 return time_gmtime(time);
2792 validate_utc_offset(off);
2793 time_set_utc_offset(time, off);
2794 return time;
2797 return time;
2800 static struct timespec
2801 time_timespec(VALUE num, int interval)
2803 struct timespec t;
2804 const char *const tstr = interval ? "time interval" : "time";
2805 VALUE i, f, ary;
2807 #ifndef NEGATIVE_TIME_T
2808 # define arg_range_check(v) \
2809 (((v) < 0) ? \
2810 rb_raise(rb_eArgError, "%s must not be negative", tstr) : \
2811 (void)0)
2812 #else
2813 # define arg_range_check(v) \
2814 ((interval && (v) < 0) ? \
2815 rb_raise(rb_eArgError, "time interval must not be negative") : \
2816 (void)0)
2817 #endif
2819 if (FIXNUM_P(num)) {
2820 t.tv_sec = NUM2TIMET(num);
2821 arg_range_check(t.tv_sec);
2822 t.tv_nsec = 0;
2824 else if (RB_FLOAT_TYPE_P(num)) {
2825 double x = RFLOAT_VALUE(num);
2826 arg_range_check(x);
2828 double f, d;
2830 d = modf(x, &f);
2831 if (d >= 0) {
2832 t.tv_nsec = (int)(d*1e9+0.5);
2833 if (t.tv_nsec >= 1000000000) {
2834 t.tv_nsec -= 1000000000;
2835 f += 1;
2838 else if ((t.tv_nsec = (int)(-d*1e9+0.5)) > 0) {
2839 t.tv_nsec = 1000000000 - t.tv_nsec;
2840 f -= 1;
2842 t.tv_sec = (time_t)f;
2843 if (f != t.tv_sec) {
2844 rb_raise(rb_eRangeError, "%f out of Time range", x);
2848 else if (RB_BIGNUM_TYPE_P(num)) {
2849 t.tv_sec = NUM2TIMET(num);
2850 arg_range_check(t.tv_sec);
2851 t.tv_nsec = 0;
2853 else {
2854 i = INT2FIX(1);
2855 ary = rb_check_funcall(num, id_divmod, 1, &i);
2856 if (!UNDEF_P(ary) && !NIL_P(ary = rb_check_array_type(ary))) {
2857 i = rb_ary_entry(ary, 0);
2858 f = rb_ary_entry(ary, 1);
2859 t.tv_sec = NUM2TIMET(i);
2860 arg_range_check(t.tv_sec);
2861 f = rb_funcall(f, '*', 1, INT2FIX(1000000000));
2862 t.tv_nsec = NUM2LONG(f);
2864 else {
2865 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into %s",
2866 rb_obj_class(num), tstr);
2869 return t;
2870 #undef arg_range_check
2873 static struct timeval
2874 time_timeval(VALUE num, int interval)
2876 struct timespec ts;
2877 struct timeval tv;
2879 ts = time_timespec(num, interval);
2880 tv.tv_sec = (TYPEOF_TIMEVAL_TV_SEC)ts.tv_sec;
2881 tv.tv_usec = (TYPEOF_TIMEVAL_TV_USEC)(ts.tv_nsec / 1000);
2883 return tv;
2886 struct timeval
2887 rb_time_interval(VALUE num)
2889 return time_timeval(num, TRUE);
2892 struct timeval
2893 rb_time_timeval(VALUE time)
2895 struct time_object *tobj;
2896 struct timeval t;
2897 struct timespec ts;
2899 if (IsTimeval(time)) {
2900 GetTimeval(time, tobj);
2901 ts = timew2timespec(tobj->timew);
2902 t.tv_sec = (TYPEOF_TIMEVAL_TV_SEC)ts.tv_sec;
2903 t.tv_usec = (TYPEOF_TIMEVAL_TV_USEC)(ts.tv_nsec / 1000);
2904 return t;
2906 return time_timeval(time, FALSE);
2909 struct timespec
2910 rb_time_timespec(VALUE time)
2912 struct time_object *tobj;
2913 struct timespec t;
2915 if (IsTimeval(time)) {
2916 GetTimeval(time, tobj);
2917 t = timew2timespec(tobj->timew);
2918 return t;
2920 return time_timespec(time, FALSE);
2923 struct timespec
2924 rb_time_timespec_interval(VALUE num)
2926 return time_timespec(num, TRUE);
2929 static int
2930 get_scale(VALUE unit)
2932 if (unit == ID2SYM(id_nanosecond) || unit == ID2SYM(id_nsec)) {
2933 return 1000000000;
2935 else if (unit == ID2SYM(id_microsecond) || unit == ID2SYM(id_usec)) {
2936 return 1000000;
2938 else if (unit == ID2SYM(id_millisecond)) {
2939 return 1000;
2941 else {
2942 rb_raise(rb_eArgError, "unexpected unit: %"PRIsVALUE, unit);
2946 static VALUE
2947 time_s_at(rb_execution_context_t *ec, VALUE klass, VALUE time, VALUE subsec, VALUE unit, VALUE zone)
2949 VALUE t;
2950 wideval_t timew;
2952 if (subsec) {
2953 int scale = get_scale(unit);
2954 time = num_exact(time);
2955 t = num_exact(subsec);
2956 timew = wadd(rb_time_magnify(v2w(time)), wmulquoll(v2w(t), TIME_SCALE, scale));
2957 t = time_new_timew(klass, timew);
2959 else if (IsTimeval(time)) {
2960 struct time_object *tobj, *tobj2;
2961 GetTimeval(time, tobj);
2962 t = time_new_timew(klass, tobj->timew);
2963 GetTimeval(t, tobj2);
2964 TZMODE_COPY(tobj2, tobj);
2966 else {
2967 timew = rb_time_magnify(v2w(num_exact(time)));
2968 t = time_new_timew(klass, timew);
2970 if (!NIL_P(zone)) {
2971 time_zonelocal(t, zone);
2974 return t;
2977 static VALUE
2978 time_s_at1(rb_execution_context_t *ec, VALUE klass, VALUE time)
2980 return time_s_at(ec, klass, time, Qfalse, ID2SYM(id_microsecond), Qnil);
2983 static const char months[][4] = {
2984 "jan", "feb", "mar", "apr", "may", "jun",
2985 "jul", "aug", "sep", "oct", "nov", "dec",
2988 static int
2989 obj2int(VALUE obj)
2991 if (RB_TYPE_P(obj, T_STRING)) {
2992 obj = rb_str_to_inum(obj, 10, TRUE);
2995 return NUM2INT(obj);
2998 /* bits should be 0 <= x <= 31 */
2999 static uint32_t
3000 obj2ubits(VALUE obj, unsigned int bits)
3002 const unsigned int usable_mask = (1U << bits) - 1;
3003 unsigned int rv = (unsigned int)obj2int(obj);
3005 if ((rv & usable_mask) != rv)
3006 rb_raise(rb_eArgError, "argument out of range");
3007 return (uint32_t)rv;
3010 static VALUE
3011 obj2vint(VALUE obj)
3013 if (RB_TYPE_P(obj, T_STRING)) {
3014 obj = rb_str_to_inum(obj, 10, TRUE);
3016 else {
3017 obj = rb_to_int(obj);
3020 return obj;
3023 static uint32_t
3024 obj2subsecx(VALUE obj, VALUE *subsecx)
3026 VALUE subsec;
3028 if (RB_TYPE_P(obj, T_STRING)) {
3029 obj = rb_str_to_inum(obj, 10, TRUE);
3030 *subsecx = INT2FIX(0);
3032 else {
3033 divmodv(num_exact(obj), INT2FIX(1), &obj, &subsec);
3034 *subsecx = w2v(rb_time_magnify(v2w(subsec)));
3036 return obj2ubits(obj, 6); /* vtm->sec */
3039 static VALUE
3040 usec2subsecx(VALUE obj)
3042 if (RB_TYPE_P(obj, T_STRING)) {
3043 obj = rb_str_to_inum(obj, 10, TRUE);
3046 return mulquov(num_exact(obj), INT2FIX(TIME_SCALE), INT2FIX(1000000));
3049 static uint32_t
3050 month_arg(VALUE arg)
3052 int i, mon;
3054 if (FIXNUM_P(arg)) {
3055 return obj2ubits(arg, 4);
3058 mon = 0;
3059 VALUE s = rb_check_string_type(arg);
3060 if (!NIL_P(s) && RSTRING_LEN(s) > 0) {
3061 arg = s;
3062 for (i=0; i<12; i++) {
3063 if (RSTRING_LEN(s) == 3 &&
3064 STRNCASECMP(months[i], RSTRING_PTR(s), 3) == 0) {
3065 mon = i+1;
3066 break;
3070 if (mon == 0) {
3071 mon = obj2ubits(arg, 4);
3073 return mon;
3076 static VALUE
3077 validate_utc_offset(VALUE utc_offset)
3079 if (le(utc_offset, INT2FIX(-86400)) || ge(utc_offset, INT2FIX(86400)))
3080 rb_raise(rb_eArgError, "utc_offset out of range");
3081 return utc_offset;
3084 static VALUE
3085 validate_zone_name(VALUE zone_name)
3087 StringValueCStr(zone_name);
3088 return zone_name;
3091 static void
3092 validate_vtm(struct vtm *vtm)
3094 #define validate_vtm_range(mem, b, e) \
3095 ((vtm->mem < b || vtm->mem > e) ? \
3096 rb_raise(rb_eArgError, #mem" out of range") : (void)0)
3097 validate_vtm_range(mon, 1, 12);
3098 validate_vtm_range(mday, 1, 31);
3099 validate_vtm_range(hour, 0, 24);
3100 validate_vtm_range(min, 0, (vtm->hour == 24 ? 0 : 59));
3101 validate_vtm_range(sec, 0, (vtm->hour == 24 ? 0 : 60));
3102 if (lt(vtm->subsecx, INT2FIX(0)) || ge(vtm->subsecx, INT2FIX(TIME_SCALE)))
3103 rb_raise(rb_eArgError, "subsecx out of range");
3104 if (!NIL_P(vtm->utc_offset)) validate_utc_offset(vtm->utc_offset);
3105 #undef validate_vtm_range
3108 static void
3109 time_arg(int argc, const VALUE *argv, struct vtm *vtm)
3111 VALUE v[8];
3112 VALUE subsecx = INT2FIX(0);
3114 vtm->year = INT2FIX(0);
3115 vtm->mon = 0;
3116 vtm->mday = 0;
3117 vtm->hour = 0;
3118 vtm->min = 0;
3119 vtm->sec = 0;
3120 vtm->subsecx = INT2FIX(0);
3121 vtm->utc_offset = Qnil;
3122 vtm->wday = 0;
3123 vtm->yday = 0;
3124 vtm->isdst = 0;
3125 vtm->zone = str_empty;
3127 if (argc == 10) {
3128 v[0] = argv[5];
3129 v[1] = argv[4];
3130 v[2] = argv[3];
3131 v[3] = argv[2];
3132 v[4] = argv[1];
3133 v[5] = argv[0];
3134 v[6] = Qnil;
3135 vtm->isdst = RTEST(argv[8]) ? 1 : 0;
3137 else {
3138 rb_scan_args(argc, argv, "17", &v[0],&v[1],&v[2],&v[3],&v[4],&v[5],&v[6],&v[7]);
3139 /* v[6] may be usec or zone (parsedate) */
3140 /* v[7] is wday (parsedate; ignored) */
3141 vtm->wday = VTM_WDAY_INITVAL;
3142 vtm->isdst = VTM_ISDST_INITVAL;
3145 vtm->year = obj2vint(v[0]);
3147 if (NIL_P(v[1])) {
3148 vtm->mon = 1;
3150 else {
3151 vtm->mon = month_arg(v[1]);
3154 if (NIL_P(v[2])) {
3155 vtm->mday = 1;
3157 else {
3158 vtm->mday = obj2ubits(v[2], 5);
3161 /* normalize month-mday */
3162 switch (vtm->mon) {
3163 case 2:
3165 /* this drops higher bits but it's not a problem to calc leap year */
3166 unsigned int mday2 = leap_year_v_p(vtm->year) ? 29 : 28;
3167 if (vtm->mday > mday2) {
3168 vtm->mday -= mday2;
3169 vtm->mon++;
3172 break;
3173 case 4:
3174 case 6:
3175 case 9:
3176 case 11:
3177 if (vtm->mday == 31) {
3178 vtm->mon++;
3179 vtm->mday = 1;
3181 break;
3184 vtm->hour = NIL_P(v[3])?0:obj2ubits(v[3], 5);
3186 vtm->min = NIL_P(v[4])?0:obj2ubits(v[4], 6);
3188 if (!NIL_P(v[6]) && argc == 7) {
3189 vtm->sec = NIL_P(v[5])?0:obj2ubits(v[5],6);
3190 subsecx = usec2subsecx(v[6]);
3192 else {
3193 /* when argc == 8, v[6] is timezone, but ignored */
3194 if (NIL_P(v[5])) {
3195 vtm->sec = 0;
3197 else {
3198 vtm->sec = obj2subsecx(v[5], &subsecx);
3201 vtm->subsecx = subsecx;
3203 validate_vtm(vtm);
3204 RB_GC_GUARD(subsecx);
3207 static int
3208 leap_year_p(long y)
3210 /* TODO:
3211 * ensure about negative years in proleptic Gregorian calendar.
3213 unsigned long uy = (unsigned long)(LIKELY(y >= 0) ? y : -y);
3215 if (LIKELY(uy % 4 != 0)) return 0;
3217 unsigned long century = uy / 100;
3218 if (LIKELY(uy != century * 100)) return 1;
3219 return century % 4 == 0;
3222 static time_t
3223 timegm_noleapsecond(struct tm *tm)
3225 long tm_year = tm->tm_year;
3226 int tm_yday = calc_tm_yday(tm->tm_year, tm->tm_mon, tm->tm_mday);
3229 * `Seconds Since the Epoch' in SUSv3:
3230 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
3231 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
3232 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
3234 return tm->tm_sec + tm->tm_min*60 + tm->tm_hour*3600 +
3235 (time_t)(tm_yday +
3236 (tm_year-70)*365 +
3237 DIV(tm_year-69,4) -
3238 DIV(tm_year-1,100) +
3239 DIV(tm_year+299,400))*86400;
3242 #if 0
3243 #define DEBUG_FIND_TIME_NUMGUESS
3244 #define DEBUG_GUESSRANGE
3245 #endif
3247 static const bool debug_guessrange =
3248 #ifdef DEBUG_GUESSRANGE
3249 true;
3250 #else
3251 false;
3252 #endif
3254 #define DEBUG_REPORT_GUESSRANGE \
3255 (debug_guessrange ? debug_report_guessrange(guess_lo, guess_hi) : (void)0)
3257 static inline void
3258 debug_report_guessrange(time_t guess_lo, time_t guess_hi)
3260 time_t guess_diff = guess_hi - guess_lo;
3261 fprintf(stderr, "find time guess range: %"PRI_TIMET_PREFIX"d - "
3262 "%"PRI_TIMET_PREFIX"d : %"PRI_TIMET_PREFIX"u\n",
3263 guess_lo, guess_hi, guess_diff);
3266 static const bool debug_find_time_numguess =
3267 #ifdef DEBUG_FIND_TIME_NUMGUESS
3268 true;
3269 #else
3270 false;
3271 #endif
3273 #define DEBUG_FIND_TIME_NUMGUESS_INC \
3274 (void)(debug_find_time_numguess && find_time_numguess++),
3275 static unsigned long long find_time_numguess;
3277 static VALUE
3278 find_time_numguess_getter(ID name, VALUE *data)
3280 unsigned long long *numguess = (void *)data;
3281 return ULL2NUM(*numguess);
3284 static const char *
3285 find_time_t(struct tm *tptr, int utc_p, time_t *tp)
3287 time_t guess, guess0, guess_lo, guess_hi;
3288 struct tm *tm, tm0, tm_lo, tm_hi;
3289 int d;
3290 int find_dst;
3291 struct tm result;
3292 int status;
3293 int tptr_tm_yday;
3295 #define GUESS(p) (DEBUG_FIND_TIME_NUMGUESS_INC (utc_p ? gmtime_with_leapsecond((p), &result) : LOCALTIME((p), result)))
3297 guess_lo = TIMET_MIN;
3298 guess_hi = TIMET_MAX;
3300 find_dst = 0 < tptr->tm_isdst;
3302 /* /etc/localtime might be changed. reload it. */
3303 update_tz();
3305 tm0 = *tptr;
3306 if (tm0.tm_mon < 0) {
3307 tm0.tm_mon = 0;
3308 tm0.tm_mday = 1;
3309 tm0.tm_hour = 0;
3310 tm0.tm_min = 0;
3311 tm0.tm_sec = 0;
3313 else if (11 < tm0.tm_mon) {
3314 tm0.tm_mon = 11;
3315 tm0.tm_mday = 31;
3316 tm0.tm_hour = 23;
3317 tm0.tm_min = 59;
3318 tm0.tm_sec = 60;
3320 else if (tm0.tm_mday < 1) {
3321 tm0.tm_mday = 1;
3322 tm0.tm_hour = 0;
3323 tm0.tm_min = 0;
3324 tm0.tm_sec = 0;
3326 else if ((d = days_in_month_in(1900 + tm0.tm_year)[tm0.tm_mon]) < tm0.tm_mday) {
3327 tm0.tm_mday = d;
3328 tm0.tm_hour = 23;
3329 tm0.tm_min = 59;
3330 tm0.tm_sec = 60;
3332 else if (tm0.tm_hour < 0) {
3333 tm0.tm_hour = 0;
3334 tm0.tm_min = 0;
3335 tm0.tm_sec = 0;
3337 else if (23 < tm0.tm_hour) {
3338 tm0.tm_hour = 23;
3339 tm0.tm_min = 59;
3340 tm0.tm_sec = 60;
3342 else if (tm0.tm_min < 0) {
3343 tm0.tm_min = 0;
3344 tm0.tm_sec = 0;
3346 else if (59 < tm0.tm_min) {
3347 tm0.tm_min = 59;
3348 tm0.tm_sec = 60;
3350 else if (tm0.tm_sec < 0) {
3351 tm0.tm_sec = 0;
3353 else if (60 < tm0.tm_sec) {
3354 tm0.tm_sec = 60;
3357 DEBUG_REPORT_GUESSRANGE;
3358 guess0 = guess = timegm_noleapsecond(&tm0);
3359 tm = GUESS(&guess);
3360 if (tm) {
3361 d = tmcmp(tptr, tm);
3362 if (d == 0) { goto found; }
3363 if (d < 0) {
3364 guess_hi = guess;
3365 guess -= 24 * 60 * 60;
3367 else {
3368 guess_lo = guess;
3369 guess += 24 * 60 * 60;
3371 DEBUG_REPORT_GUESSRANGE;
3372 if (guess_lo < guess && guess < guess_hi && (tm = GUESS(&guess)) != NULL) {
3373 d = tmcmp(tptr, tm);
3374 if (d == 0) { goto found; }
3375 if (d < 0)
3376 guess_hi = guess;
3377 else
3378 guess_lo = guess;
3379 DEBUG_REPORT_GUESSRANGE;
3383 tm = GUESS(&guess_lo);
3384 if (!tm) goto error;
3385 d = tmcmp(tptr, tm);
3386 if (d < 0) goto out_of_range;
3387 if (d == 0) { guess = guess_lo; goto found; }
3388 tm_lo = *tm;
3390 tm = GUESS(&guess_hi);
3391 if (!tm) goto error;
3392 d = tmcmp(tptr, tm);
3393 if (d > 0) goto out_of_range;
3394 if (d == 0) { guess = guess_hi; goto found; }
3395 tm_hi = *tm;
3397 DEBUG_REPORT_GUESSRANGE;
3399 status = 1;
3401 while (guess_lo + 1 < guess_hi) {
3402 binsearch:
3403 if (status == 0) {
3404 guess = guess_lo / 2 + guess_hi / 2;
3405 if (guess <= guess_lo)
3406 guess = guess_lo + 1;
3407 else if (guess >= guess_hi)
3408 guess = guess_hi - 1;
3409 status = 1;
3411 else {
3412 if (status == 1) {
3413 time_t guess0_hi = timegm_noleapsecond(&tm_hi);
3414 guess = guess_hi - (guess0_hi - guess0);
3415 if (guess == guess_hi) /* hh:mm:60 tends to cause this condition. */
3416 guess--;
3417 status = 2;
3419 else if (status == 2) {
3420 time_t guess0_lo = timegm_noleapsecond(&tm_lo);
3421 guess = guess_lo + (guess0 - guess0_lo);
3422 if (guess == guess_lo)
3423 guess++;
3424 status = 0;
3426 if (guess <= guess_lo || guess_hi <= guess) {
3427 /* Previous guess is invalid. try binary search. */
3428 if (debug_guessrange) {
3429 if (guess <= guess_lo) {
3430 fprintf(stderr, "too small guess: %"PRI_TIMET_PREFIX"d"\
3431 " <= %"PRI_TIMET_PREFIX"d\n", guess, guess_lo);
3433 if (guess_hi <= guess) {
3434 fprintf(stderr, "too big guess: %"PRI_TIMET_PREFIX"d"\
3435 " <= %"PRI_TIMET_PREFIX"d\n", guess_hi, guess);
3438 status = 0;
3439 goto binsearch;
3443 tm = GUESS(&guess);
3444 if (!tm) goto error;
3446 d = tmcmp(tptr, tm);
3448 if (d < 0) {
3449 guess_hi = guess;
3450 tm_hi = *tm;
3451 DEBUG_REPORT_GUESSRANGE;
3453 else if (d > 0) {
3454 guess_lo = guess;
3455 tm_lo = *tm;
3456 DEBUG_REPORT_GUESSRANGE;
3458 else {
3459 goto found;
3463 /* Given argument has no corresponding time_t. Let's extrapolate. */
3465 * `Seconds Since the Epoch' in SUSv3:
3466 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
3467 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
3468 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
3471 tptr_tm_yday = calc_tm_yday(tptr->tm_year, tptr->tm_mon, tptr->tm_mday);
3473 *tp = guess_lo +
3474 ((tptr->tm_year - tm_lo.tm_year) * 365 +
3475 DIV((tptr->tm_year-69), 4) -
3476 DIV((tptr->tm_year-1), 100) +
3477 DIV((tptr->tm_year+299), 400) -
3478 DIV((tm_lo.tm_year-69), 4) +
3479 DIV((tm_lo.tm_year-1), 100) -
3480 DIV((tm_lo.tm_year+299), 400) +
3481 tptr_tm_yday -
3482 tm_lo.tm_yday) * 86400 +
3483 (tptr->tm_hour - tm_lo.tm_hour) * 3600 +
3484 (tptr->tm_min - tm_lo.tm_min) * 60 +
3485 (tptr->tm_sec - (tm_lo.tm_sec == 60 ? 59 : tm_lo.tm_sec));
3487 return NULL;
3489 found:
3490 if (!utc_p) {
3491 /* If localtime is nonmonotonic, another result may exist. */
3492 time_t guess2;
3493 if (find_dst) {
3494 guess2 = guess - 2 * 60 * 60;
3495 tm = LOCALTIME(&guess2, result);
3496 if (tm) {
3497 if (tptr->tm_hour != (tm->tm_hour + 2) % 24 ||
3498 tptr->tm_min != tm->tm_min ||
3499 tptr->tm_sec != tm->tm_sec) {
3500 guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
3501 (tm->tm_min - tptr->tm_min) * 60 +
3502 (tm->tm_sec - tptr->tm_sec);
3503 if (tptr->tm_mday != tm->tm_mday)
3504 guess2 += 24 * 60 * 60;
3505 if (guess != guess2) {
3506 tm = LOCALTIME(&guess2, result);
3507 if (tm && tmcmp(tptr, tm) == 0) {
3508 if (guess < guess2)
3509 *tp = guess;
3510 else
3511 *tp = guess2;
3512 return NULL;
3518 else {
3519 guess2 = guess + 2 * 60 * 60;
3520 tm = LOCALTIME(&guess2, result);
3521 if (tm) {
3522 if ((tptr->tm_hour + 2) % 24 != tm->tm_hour ||
3523 tptr->tm_min != tm->tm_min ||
3524 tptr->tm_sec != tm->tm_sec) {
3525 guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
3526 (tm->tm_min - tptr->tm_min) * 60 +
3527 (tm->tm_sec - tptr->tm_sec);
3528 if (tptr->tm_mday != tm->tm_mday)
3529 guess2 -= 24 * 60 * 60;
3530 if (guess != guess2) {
3531 tm = LOCALTIME(&guess2, result);
3532 if (tm && tmcmp(tptr, tm) == 0) {
3533 if (guess < guess2)
3534 *tp = guess2;
3535 else
3536 *tp = guess;
3537 return NULL;
3544 *tp = guess;
3545 return NULL;
3547 out_of_range:
3548 return "time out of range";
3550 error:
3551 return "gmtime/localtime error";
3554 static int
3555 vtmcmp(struct vtm *a, struct vtm *b)
3557 if (ne(a->year, b->year))
3558 return lt(a->year, b->year) ? -1 : 1;
3559 else if (a->mon != b->mon)
3560 return a->mon < b->mon ? -1 : 1;
3561 else if (a->mday != b->mday)
3562 return a->mday < b->mday ? -1 : 1;
3563 else if (a->hour != b->hour)
3564 return a->hour < b->hour ? -1 : 1;
3565 else if (a->min != b->min)
3566 return a->min < b->min ? -1 : 1;
3567 else if (a->sec != b->sec)
3568 return a->sec < b->sec ? -1 : 1;
3569 else if (ne(a->subsecx, b->subsecx))
3570 return lt(a->subsecx, b->subsecx) ? -1 : 1;
3571 else
3572 return 0;
3575 static int
3576 tmcmp(struct tm *a, struct tm *b)
3578 if (a->tm_year != b->tm_year)
3579 return a->tm_year < b->tm_year ? -1 : 1;
3580 else if (a->tm_mon != b->tm_mon)
3581 return a->tm_mon < b->tm_mon ? -1 : 1;
3582 else if (a->tm_mday != b->tm_mday)
3583 return a->tm_mday < b->tm_mday ? -1 : 1;
3584 else if (a->tm_hour != b->tm_hour)
3585 return a->tm_hour < b->tm_hour ? -1 : 1;
3586 else if (a->tm_min != b->tm_min)
3587 return a->tm_min < b->tm_min ? -1 : 1;
3588 else if (a->tm_sec != b->tm_sec)
3589 return a->tm_sec < b->tm_sec ? -1 : 1;
3590 else
3591 return 0;
3595 * call-seq:
3596 * Time.utc(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0) -> new_time
3597 * Time.utc(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy) -> new_time
3599 * Returns a new +Time+ object based the on given arguments,
3600 * in the UTC timezone.
3602 * With one to seven arguments given,
3603 * the arguments are interpreted as in the first calling sequence above:
3605 * Time.utc(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0)
3607 * Examples:
3609 * Time.utc(2000) # => 2000-01-01 00:00:00 UTC
3610 * Time.utc(-2000) # => -2000-01-01 00:00:00 UTC
3612 * There are no minimum and maximum values for the required argument +year+.
3614 * For the optional arguments:
3616 * - +month+: Month in range (1..12), or case-insensitive
3617 * 3-letter month name:
3619 * Time.utc(2000, 1) # => 2000-01-01 00:00:00 UTC
3620 * Time.utc(2000, 12) # => 2000-12-01 00:00:00 UTC
3621 * Time.utc(2000, 'jan') # => 2000-01-01 00:00:00 UTC
3622 * Time.utc(2000, 'JAN') # => 2000-01-01 00:00:00 UTC
3624 * - +mday+: Month day in range(1..31):
3626 * Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC
3627 * Time.utc(2000, 1, 31) # => 2000-01-31 00:00:00 UTC
3629 * - +hour+: Hour in range (0..23), or 24 if +min+, +sec+, and +usec+
3630 * are zero:
3632 * Time.utc(2000, 1, 1, 0) # => 2000-01-01 00:00:00 UTC
3633 * Time.utc(2000, 1, 1, 23) # => 2000-01-01 23:00:00 UTC
3634 * Time.utc(2000, 1, 1, 24) # => 2000-01-02 00:00:00 UTC
3636 * - +min+: Minute in range (0..59):
3638 * Time.utc(2000, 1, 1, 0, 0) # => 2000-01-01 00:00:00 UTC
3639 * Time.utc(2000, 1, 1, 0, 59) # => 2000-01-01 00:59:00 UTC
3641 * - +sec+: Second in range (0..59), or 60 if +usec+ is zero:
3643 * Time.utc(2000, 1, 1, 0, 0, 0) # => 2000-01-01 00:00:00 UTC
3644 * Time.utc(2000, 1, 1, 0, 0, 59) # => 2000-01-01 00:00:59 UTC
3645 * Time.utc(2000, 1, 1, 0, 0, 60) # => 2000-01-01 00:01:00 UTC
3647 * - +usec+: Microsecond in range (0..999999):
3649 * Time.utc(2000, 1, 1, 0, 0, 0, 0) # => 2000-01-01 00:00:00 UTC
3650 * Time.utc(2000, 1, 1, 0, 0, 0, 999999) # => 2000-01-01 00:00:00.999999 UTC
3652 * The values may be:
3654 * - Integers, as above.
3655 * - Numerics convertible to integers:
3657 * Time.utc(Float(0.0), Rational(1, 1), 1.0, 0.0, 0.0, 0.0, 0.0)
3658 * # => 0000-01-01 00:00:00 UTC
3660 * - String integers:
3662 * a = %w[0 1 1 0 0 0 0 0]
3663 * # => ["0", "1", "1", "0", "0", "0", "0", "0"]
3664 * Time.utc(*a) # => 0000-01-01 00:00:00 UTC
3666 * When exactly ten arguments are given,
3667 * the arguments are interpreted as in the second calling sequence above:
3669 * Time.utc(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy)
3671 * where the +dummy+ arguments are ignored:
3673 * a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3674 * # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3675 * Time.utc(*a) # => 0005-04-03 02:01:00 UTC
3677 * This form is useful for creating a +Time+ object from a 10-element
3678 * array returned by Time.to_a:
3680 * t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006
3681 * a = t.to_a # => [5, 4, 3, 2, 1, 2000, 0, 2, false, nil]
3682 * Time.utc(*a) # => 2000-01-02 03:04:05 UTC
3684 * The two forms have their first six arguments in common,
3685 * though in different orders;
3686 * the ranges of these common arguments are the same for both forms; see above.
3688 * Raises an exception if the number of arguments is eight, nine,
3689 * or greater than ten.
3691 * Related: Time.local.
3694 static VALUE
3695 time_s_mkutc(int argc, VALUE *argv, VALUE klass)
3697 struct vtm vtm;
3699 time_arg(argc, argv, &vtm);
3700 return time_gmtime(time_new_timew(klass, timegmw(&vtm)));
3704 * call-seq:
3705 * Time.local(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0) -> new_time
3706 * Time.local(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy) -> new_time
3708 * Like Time.utc, except that the returned +Time+ object
3709 * has the local timezone, not the UTC timezone:
3711 * # With seven arguments.
3712 * Time.local(0, 1, 2, 3, 4, 5, 6)
3713 * # => 0000-01-02 03:04:05.000006 -0600
3714 * # With exactly ten arguments.
3715 * Time.local(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
3716 * # => 0005-04-03 02:01:00 -0600
3720 static VALUE
3721 time_s_mktime(int argc, VALUE *argv, VALUE klass)
3723 struct vtm vtm;
3725 time_arg(argc, argv, &vtm);
3726 return time_localtime(time_new_timew(klass, timelocalw(&vtm)));
3730 * call-seq:
3731 * to_i -> integer
3733 * Returns the value of +self+ as integer
3734 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3735 * subseconds are truncated (not rounded):
3737 * Time.utc(1970, 1, 1, 0, 0, 0).to_i # => 0
3738 * Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_i # => 0
3739 * Time.utc(1950, 1, 1, 0, 0, 0).to_i # => -631152000
3740 * Time.utc(1990, 1, 1, 0, 0, 0).to_i # => 631152000
3742 * Related: Time#to_f Time#to_r.
3745 static VALUE
3746 time_to_i(VALUE time)
3748 struct time_object *tobj;
3750 GetTimeval(time, tobj);
3751 return w2v(wdiv(tobj->timew, WINT2FIXWV(TIME_SCALE)));
3755 * call-seq:
3756 * to_f -> float
3758 * Returns the value of +self+ as a Float number
3759 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3760 * subseconds are included.
3762 * The stored value of +self+ is a
3763 * {Rational}[rdoc-ref:Rational@#method-i-to_f],
3764 * which means that the returned value may be approximate:
3766 * Time.utc(1970, 1, 1, 0, 0, 0).to_f # => 0.0
3767 * Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_f # => 0.999999
3768 * Time.utc(1950, 1, 1, 0, 0, 0).to_f # => -631152000.0
3769 * Time.utc(1990, 1, 1, 0, 0, 0).to_f # => 631152000.0
3771 * Related: Time#to_i, Time#to_r.
3774 static VALUE
3775 time_to_f(VALUE time)
3777 struct time_object *tobj;
3779 GetTimeval(time, tobj);
3780 return rb_Float(rb_time_unmagnify_to_float(tobj->timew));
3784 * call-seq:
3785 * to_r -> rational
3787 * Returns the value of +self+ as a Rational exact number of
3788 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3790 * Time.now.to_r # => (16571402750320203/10000000)
3792 * Related: Time#to_f, Time#to_i.
3795 static VALUE
3796 time_to_r(VALUE time)
3798 struct time_object *tobj;
3799 VALUE v;
3801 GetTimeval(time, tobj);
3802 v = rb_time_unmagnify_to_rational(tobj->timew);
3803 if (!RB_TYPE_P(v, T_RATIONAL)) {
3804 v = rb_Rational1(v);
3806 return v;
3810 * call-seq:
3811 * usec -> integer
3813 * Returns the number of microseconds in the subseconds part of +self+
3814 * in the range (0..999_999);
3815 * lower-order digits are truncated, not rounded:
3817 * t = Time.now # => 2022-07-11 14:59:47.5484697 -0500
3818 * t.usec # => 548469
3820 * Related: Time#subsec (returns exact subseconds).
3823 static VALUE
3824 time_usec(VALUE time)
3826 struct time_object *tobj;
3827 wideval_t w, q, r;
3829 GetTimeval(time, tobj);
3831 w = wmod(tobj->timew, WINT2WV(TIME_SCALE));
3832 wmuldivmod(w, WINT2FIXWV(1000000), WINT2FIXWV(TIME_SCALE), &q, &r);
3833 return rb_to_int(w2v(q));
3837 * call-seq:
3838 * nsec -> integer
3840 * Returns the number of nanoseconds in the subseconds part of +self+
3841 * in the range (0..999_999_999);
3842 * lower-order digits are truncated, not rounded:
3844 * t = Time.now # => 2022-07-11 15:04:53.3219637 -0500
3845 * t.nsec # => 321963700
3847 * Related: Time#subsec (returns exact subseconds).
3850 static VALUE
3851 time_nsec(VALUE time)
3853 struct time_object *tobj;
3855 GetTimeval(time, tobj);
3856 return rb_to_int(w2v(wmulquoll(wmod(tobj->timew, WINT2WV(TIME_SCALE)), 1000000000, TIME_SCALE)));
3860 * call-seq:
3861 * subsec -> numeric
3863 * Returns the exact subseconds for +self+ as a Numeric
3864 * (Integer or Rational):
3866 * t = Time.now # => 2022-07-11 15:11:36.8490302 -0500
3867 * t.subsec # => (4245151/5000000)
3869 * If the subseconds is zero, returns integer zero:
3871 * t = Time.new(2000, 1, 1, 2, 3, 4) # => 2000-01-01 02:03:04 -0600
3872 * t.subsec # => 0
3876 static VALUE
3877 time_subsec(VALUE time)
3879 struct time_object *tobj;
3881 GetTimeval(time, tobj);
3882 return quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE));
3886 * call-seq:
3887 * self <=> other_time -> -1, 0, +1, or nil
3889 * Compares +self+ with +other_time+; returns:
3891 * - +-1+, if +self+ is less than +other_time+.
3892 * - +0+, if +self+ is equal to +other_time+.
3893 * - +1+, if +self+ is greater then +other_time+.
3894 * - +nil+, if +self+ and +other_time+ are incomparable.
3896 * Examples:
3898 * t = Time.now # => 2007-11-19 08:12:12 -0600
3899 * t2 = t + 2592000 # => 2007-12-19 08:12:12 -0600
3900 * t <=> t2 # => -1
3901 * t2 <=> t # => 1
3903 * t = Time.now # => 2007-11-19 08:13:38 -0600
3904 * t2 = t + 0.1 # => 2007-11-19 08:13:38 -0600
3905 * t.nsec # => 98222999
3906 * t2.nsec # => 198222999
3907 * t <=> t2 # => -1
3908 * t2 <=> t # => 1
3909 * t <=> t # => 0
3913 static VALUE
3914 time_cmp(VALUE time1, VALUE time2)
3916 struct time_object *tobj1, *tobj2;
3917 int n;
3919 GetTimeval(time1, tobj1);
3920 if (IsTimeval(time2)) {
3921 GetTimeval(time2, tobj2);
3922 n = wcmp(tobj1->timew, tobj2->timew);
3924 else {
3925 return rb_invcmp(time1, time2);
3927 if (n == 0) return INT2FIX(0);
3928 if (n > 0) return INT2FIX(1);
3929 return INT2FIX(-1);
3933 * call-seq:
3934 * eql?(other_time)
3936 * Returns +true+ if +self+ and +other_time+ are
3937 * both +Time+ objects with the exact same time value.
3940 static VALUE
3941 time_eql(VALUE time1, VALUE time2)
3943 struct time_object *tobj1, *tobj2;
3945 GetTimeval(time1, tobj1);
3946 if (IsTimeval(time2)) {
3947 GetTimeval(time2, tobj2);
3948 return rb_equal(w2v(tobj1->timew), w2v(tobj2->timew));
3950 return Qfalse;
3954 * call-seq:
3955 * utc? -> true or false
3957 * Returns +true+ if +self+ represents a time in UTC (GMT):
3959 * now = Time.now
3960 * # => 2022-08-18 10:24:13.5398485 -0500
3961 * now.utc? # => false
3962 * utc = Time.utc(2000, 1, 1, 20, 15, 1)
3963 * # => 2000-01-01 20:15:01 UTC
3964 * utc.utc? # => true
3966 * Related: Time.utc.
3969 static VALUE
3970 time_utc_p(VALUE time)
3972 struct time_object *tobj;
3974 GetTimeval(time, tobj);
3975 return RBOOL(TZMODE_UTC_P(tobj));
3979 * call-seq:
3980 * hash -> integer
3982 * Returns the integer hash code for +self+.
3984 * Related: Object#hash.
3987 static VALUE
3988 time_hash(VALUE time)
3990 struct time_object *tobj;
3992 GetTimeval(time, tobj);
3993 return rb_hash(w2v(tobj->timew));
3996 /* :nodoc: */
3997 static VALUE
3998 time_init_copy(VALUE copy, VALUE time)
4000 struct time_object *tobj, *tcopy;
4002 if (!OBJ_INIT_COPY(copy, time)) return copy;
4003 GetTimeval(time, tobj);
4004 GetNewTimeval(copy, tcopy);
4005 MEMCPY(tcopy, tobj, struct time_object, 1);
4007 return copy;
4010 static VALUE
4011 time_dup(VALUE time)
4013 VALUE dup = time_s_alloc(rb_obj_class(time));
4014 time_init_copy(dup, time);
4015 return dup;
4018 static VALUE
4019 time_localtime(VALUE time)
4021 struct time_object *tobj;
4022 struct vtm vtm;
4023 VALUE zone;
4025 GetTimeval(time, tobj);
4026 if (TZMODE_LOCALTIME_P(tobj)) {
4027 if (tobj->vtm.tm_got)
4028 return time;
4030 else {
4031 time_modify(time);
4034 zone = tobj->vtm.zone;
4035 if (maybe_tzobj_p(zone) && zone_localtime(zone, time)) {
4036 return time;
4039 if (!localtimew(tobj->timew, &vtm))
4040 rb_raise(rb_eArgError, "localtime error");
4041 time_set_vtm(time, tobj, vtm);
4043 tobj->vtm.tm_got = 1;
4044 TZMODE_SET_LOCALTIME(tobj);
4045 return time;
4048 static VALUE
4049 time_zonelocal(VALUE time, VALUE off)
4051 VALUE zone = off;
4052 if (zone_localtime(zone, time)) return time;
4054 if (NIL_P(off = utc_offset_arg(off))) {
4055 off = zone;
4056 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
4057 if (!zone_localtime(zone, time)) invalid_utc_offset(off);
4058 return time;
4060 else if (off == UTC_ZONE) {
4061 return time_gmtime(time);
4063 validate_utc_offset(off);
4065 time_set_utc_offset(time, off);
4066 return time_fixoff(time);
4070 * call-seq:
4071 * localtime -> self or new_time
4072 * localtime(zone) -> new_time
4074 * With no argument given:
4076 * - Returns +self+ if +self+ is a local time.
4077 * - Otherwise returns a new +Time+ in the user's local timezone:
4079 * t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC
4080 * t.localtime # => 2000-01-01 14:15:01 -0600
4082 * With argument +zone+ given,
4083 * returns the new +Time+ object created by converting
4084 * +self+ to the given time zone:
4086 * t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC
4087 * t.localtime("-09:00") # => 2000-01-01 11:15:01 -0900
4089 * For forms of argument +zone+, see
4090 * {Timezone Specifiers}[rdoc-ref:Time@Timezone+Specifiers].
4094 static VALUE
4095 time_localtime_m(int argc, VALUE *argv, VALUE time)
4097 VALUE off;
4099 if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
4100 return time_zonelocal(time, off);
4103 return time_localtime(time);
4107 * call-seq:
4108 * utc -> self
4110 * Returns +self+, converted to the UTC timezone:
4112 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4113 * t.utc? # => false
4114 * t.utc # => 2000-01-01 06:00:00 UTC
4115 * t.utc? # => true
4117 * Related: Time#getutc (returns a new converted +Time+ object).
4120 static VALUE
4121 time_gmtime(VALUE time)
4123 struct time_object *tobj;
4124 struct vtm vtm;
4126 GetTimeval(time, tobj);
4127 if (TZMODE_UTC_P(tobj)) {
4128 if (tobj->vtm.tm_got)
4129 return time;
4131 else {
4132 time_modify(time);
4135 vtm.zone = str_utc;
4136 GMTIMEW(tobj->timew, &vtm);
4137 time_set_vtm(time, tobj, vtm);
4139 tobj->vtm.tm_got = 1;
4140 TZMODE_SET_UTC(tobj);
4141 return time;
4144 static VALUE
4145 time_fixoff(VALUE time)
4147 struct time_object *tobj;
4148 struct vtm vtm;
4149 VALUE off, zone;
4151 GetTimeval(time, tobj);
4152 if (TZMODE_FIXOFF_P(tobj)) {
4153 if (tobj->vtm.tm_got)
4154 return time;
4156 else {
4157 time_modify(time);
4160 if (TZMODE_FIXOFF_P(tobj))
4161 off = tobj->vtm.utc_offset;
4162 else
4163 off = INT2FIX(0);
4165 GMTIMEW(tobj->timew, &vtm);
4167 zone = tobj->vtm.zone;
4168 vtm_add_offset(&vtm, off, +1);
4170 time_set_vtm(time, tobj, vtm);
4171 RB_OBJ_WRITE_UNALIGNED(time, &tobj->vtm.zone, zone);
4173 tobj->vtm.tm_got = 1;
4174 TZMODE_SET_FIXOFF(time, tobj, off);
4175 return time;
4179 * call-seq:
4180 * getlocal(zone = nil) -> new_time
4182 * Returns a new +Time+ object representing the value of +self+
4183 * converted to a given timezone;
4184 * if +zone+ is +nil+, the local timezone is used:
4186 * t = Time.utc(2000) # => 2000-01-01 00:00:00 UTC
4187 * t.getlocal # => 1999-12-31 18:00:00 -0600
4188 * t.getlocal('+12:00') # => 2000-01-01 12:00:00 +1200
4190 * For forms of argument +zone+, see
4191 * {Timezone Specifiers}[rdoc-ref:Time@Timezone+Specifiers].
4195 static VALUE
4196 time_getlocaltime(int argc, VALUE *argv, VALUE time)
4198 VALUE off;
4200 if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
4201 VALUE zone = off;
4202 if (maybe_tzobj_p(zone)) {
4203 VALUE t = time_dup(time);
4204 if (zone_localtime(off, t)) return t;
4207 if (NIL_P(off = utc_offset_arg(off))) {
4208 off = zone;
4209 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
4210 time = time_dup(time);
4211 if (!zone_localtime(zone, time)) invalid_utc_offset(off);
4212 return time;
4214 else if (off == UTC_ZONE) {
4215 return time_gmtime(time_dup(time));
4217 validate_utc_offset(off);
4219 time = time_dup(time);
4220 time_set_utc_offset(time, off);
4221 return time_fixoff(time);
4224 return time_localtime(time_dup(time));
4228 * call-seq:
4229 * getutc -> new_time
4231 * Returns a new +Time+ object representing the value of +self+
4232 * converted to the UTC timezone:
4234 * local = Time.local(2000) # => 2000-01-01 00:00:00 -0600
4235 * local.utc? # => false
4236 * utc = local.getutc # => 2000-01-01 06:00:00 UTC
4237 * utc.utc? # => true
4238 * utc == local # => true
4242 static VALUE
4243 time_getgmtime(VALUE time)
4245 return time_gmtime(time_dup(time));
4248 static VALUE
4249 time_get_tm(VALUE time, struct time_object *tobj)
4251 if (TZMODE_UTC_P(tobj)) return time_gmtime(time);
4252 if (TZMODE_FIXOFF_P(tobj)) return time_fixoff(time);
4253 return time_localtime(time);
4256 static VALUE strftime_cstr(const char *fmt, size_t len, VALUE time, rb_encoding *enc);
4257 #define strftimev(fmt, time, enc) strftime_cstr((fmt), rb_strlen_lit(fmt), (time), (enc))
4260 * call-seq:
4261 * ctime -> string
4263 * Returns a string representation of +self+,
4264 * formatted by <tt>strftime('%a %b %e %T %Y')</tt>
4265 * or its shorthand version <tt>strftime('%c')</tt>;
4266 * see {Formats for Dates and Times}[rdoc-ref:strftime_formatting.rdoc]:
4268 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4269 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4270 * t.strftime('%a %b %e %T %Y') # => "Sun Dec 31 23:59:59 2000"
4271 * t.strftime('%c') # => "Sun Dec 31 23:59:59 2000"
4273 * Related: Time#to_s, Time#inspect:
4275 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4276 * t.to_s # => "2000-12-31 23:59:59 +0000"
4280 static VALUE
4281 time_asctime(VALUE time)
4283 return strftimev("%a %b %e %T %Y", time, rb_usascii_encoding());
4287 * call-seq:
4288 * to_s -> string
4290 * Returns a string representation of +self+, without subseconds:
4292 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4293 * t.to_s # => "2000-12-31 23:59:59 +0000"
4295 * Related: Time#ctime, Time#inspect:
4297 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4298 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4302 static VALUE
4303 time_to_s(VALUE time)
4305 struct time_object *tobj;
4307 GetTimeval(time, tobj);
4308 if (TZMODE_UTC_P(tobj))
4309 return strftimev("%Y-%m-%d %H:%M:%S UTC", time, rb_usascii_encoding());
4310 else
4311 return strftimev("%Y-%m-%d %H:%M:%S %z", time, rb_usascii_encoding());
4315 * call-seq:
4316 * inspect -> string
4318 * Returns a string representation of +self+ with subseconds:
4320 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4321 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4323 * Related: Time#ctime, Time#to_s:
4325 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4326 * t.to_s # => "2000-12-31 23:59:59 +0000"
4330 static VALUE
4331 time_inspect(VALUE time)
4333 struct time_object *tobj;
4334 VALUE str, subsec;
4336 GetTimeval(time, tobj);
4337 str = strftimev("%Y-%m-%d %H:%M:%S", time, rb_usascii_encoding());
4338 subsec = w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE)));
4339 if (subsec == INT2FIX(0)) {
4341 else if (FIXNUM_P(subsec) && FIX2LONG(subsec) < TIME_SCALE) {
4342 long len;
4343 rb_str_catf(str, ".%09ld", FIX2LONG(subsec));
4344 for (len=RSTRING_LEN(str); RSTRING_PTR(str)[len-1] == '0' && len > 0; len--)
4346 rb_str_resize(str, len);
4348 else {
4349 rb_str_cat_cstr(str, " ");
4350 subsec = quov(subsec, INT2FIX(TIME_SCALE));
4351 rb_str_concat(str, rb_obj_as_string(subsec));
4353 if (TZMODE_UTC_P(tobj)) {
4354 rb_str_cat_cstr(str, " UTC");
4356 else {
4357 /* ?TODO: subsecond offset */
4358 long off = NUM2LONG(rb_funcall(tobj->vtm.utc_offset, rb_intern("round"), 0));
4359 char sign = (off < 0) ? (off = -off, '-') : '+';
4360 int sec = off % 60;
4361 int min = (off /= 60) % 60;
4362 off /= 60;
4363 rb_str_catf(str, " %c%.2d%.2d", sign, (int)off, min);
4364 if (sec) rb_str_catf(str, "%.2d", sec);
4366 return str;
4369 static VALUE
4370 time_add0(VALUE klass, const struct time_object *tobj, VALUE torig, VALUE offset, int sign)
4372 VALUE result;
4373 struct time_object *result_tobj;
4375 offset = num_exact(offset);
4376 if (sign < 0)
4377 result = time_new_timew(klass, wsub(tobj->timew, rb_time_magnify(v2w(offset))));
4378 else
4379 result = time_new_timew(klass, wadd(tobj->timew, rb_time_magnify(v2w(offset))));
4380 GetTimeval(result, result_tobj);
4381 TZMODE_COPY(result_tobj, tobj);
4383 return result;
4386 static VALUE
4387 time_add(const struct time_object *tobj, VALUE torig, VALUE offset, int sign)
4389 return time_add0(rb_cTime, tobj, torig, offset, sign);
4393 * call-seq:
4394 * self + numeric -> new_time
4396 * Returns a new +Time+ object whose value is the sum of the numeric value
4397 * of +self+ and the given +numeric+:
4399 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4400 * t + (60 * 60 * 24) # => 2000-01-02 00:00:00 -0600
4401 * t + 0.5 # => 2000-01-01 00:00:00.5 -0600
4403 * Related: Time#-.
4406 static VALUE
4407 time_plus(VALUE time1, VALUE time2)
4409 struct time_object *tobj;
4410 GetTimeval(time1, tobj);
4412 if (IsTimeval(time2)) {
4413 rb_raise(rb_eTypeError, "time + time?");
4415 return time_add(tobj, time1, time2, 1);
4419 * call-seq:
4420 * self - numeric -> new_time
4421 * self - other_time -> float
4423 * When +numeric+ is given,
4424 * returns a new +Time+ object whose value is the difference
4425 * of the numeric value of +self+ and +numeric+:
4427 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4428 * t - (60 * 60 * 24) # => 1999-12-31 00:00:00 -0600
4429 * t - 0.5 # => 1999-12-31 23:59:59.5 -0600
4431 * When +other_time+ is given,
4432 * returns a Float whose value is the difference
4433 * of the numeric values of +self+ and +other_time+ in seconds:
4435 * t - t # => 0.0
4437 * Related: Time#+.
4440 static VALUE
4441 time_minus(VALUE time1, VALUE time2)
4443 struct time_object *tobj;
4445 GetTimeval(time1, tobj);
4446 if (IsTimeval(time2)) {
4447 struct time_object *tobj2;
4449 GetTimeval(time2, tobj2);
4450 return rb_Float(rb_time_unmagnify_to_float(wsub(tobj->timew, tobj2->timew)));
4452 return time_add(tobj, time1, time2, -1);
4455 static VALUE
4456 ndigits_denominator(VALUE ndigits)
4458 long nd = NUM2LONG(ndigits);
4460 if (nd < 0) {
4461 rb_raise(rb_eArgError, "negative ndigits given");
4463 if (nd == 0) {
4464 return INT2FIX(1);
4466 return rb_rational_new(INT2FIX(1),
4467 rb_int_positive_pow(10, (unsigned long)nd));
4471 * call-seq:
4472 * round(ndigits = 0) -> new_time
4474 * Returns a new +Time+ object whose numeric value is that of +self+,
4475 * with its seconds value rounded to precision +ndigits+:
4477 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4478 * t # => 2010-03-30 05:43:25.123456789 UTC
4479 * t.round # => 2010-03-30 05:43:25 UTC
4480 * t.round(0) # => 2010-03-30 05:43:25 UTC
4481 * t.round(1) # => 2010-03-30 05:43:25.1 UTC
4482 * t.round(2) # => 2010-03-30 05:43:25.12 UTC
4483 * t.round(3) # => 2010-03-30 05:43:25.123 UTC
4484 * t.round(4) # => 2010-03-30 05:43:25.1235 UTC
4486 * t = Time.utc(1999, 12,31, 23, 59, 59)
4487 * t # => 1999-12-31 23:59:59 UTC
4488 * (t + 0.4).round # => 1999-12-31 23:59:59 UTC
4489 * (t + 0.49).round # => 1999-12-31 23:59:59 UTC
4490 * (t + 0.5).round # => 2000-01-01 00:00:00 UTC
4491 * (t + 1.4).round # => 2000-01-01 00:00:00 UTC
4492 * (t + 1.49).round # => 2000-01-01 00:00:00 UTC
4493 * (t + 1.5).round # => 2000-01-01 00:00:01 UTC
4495 * Related: Time#ceil, Time#floor.
4498 static VALUE
4499 time_round(int argc, VALUE *argv, VALUE time)
4501 VALUE ndigits, v, den;
4502 struct time_object *tobj;
4504 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4505 den = INT2FIX(1);
4506 else
4507 den = ndigits_denominator(ndigits);
4509 GetTimeval(time, tobj);
4510 v = w2v(rb_time_unmagnify(tobj->timew));
4512 v = modv(v, den);
4513 if (lt(v, quov(den, INT2FIX(2))))
4514 return time_add(tobj, time, v, -1);
4515 else
4516 return time_add(tobj, time, subv(den, v), 1);
4520 * call-seq:
4521 * floor(ndigits = 0) -> new_time
4523 * Returns a new +Time+ object whose numerical value
4524 * is less than or equal to +self+ with its seconds
4525 * truncated to precision +ndigits+:
4527 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4528 * t # => 2010-03-30 05:43:25.123456789 UTC
4529 * t.floor # => 2010-03-30 05:43:25 UTC
4530 * t.floor(2) # => 2010-03-30 05:43:25.12 UTC
4531 * t.floor(4) # => 2010-03-30 05:43:25.1234 UTC
4532 * t.floor(6) # => 2010-03-30 05:43:25.123456 UTC
4533 * t.floor(8) # => 2010-03-30 05:43:25.12345678 UTC
4534 * t.floor(10) # => 2010-03-30 05:43:25.123456789 UTC
4536 * t = Time.utc(1999, 12, 31, 23, 59, 59)
4537 * t # => 1999-12-31 23:59:59 UTC
4538 * (t + 0.4).floor # => 1999-12-31 23:59:59 UTC
4539 * (t + 0.9).floor # => 1999-12-31 23:59:59 UTC
4540 * (t + 1.4).floor # => 2000-01-01 00:00:00 UTC
4541 * (t + 1.9).floor # => 2000-01-01 00:00:00 UTC
4543 * Related: Time#ceil, Time#round.
4546 static VALUE
4547 time_floor(int argc, VALUE *argv, VALUE time)
4549 VALUE ndigits, v, den;
4550 struct time_object *tobj;
4552 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4553 den = INT2FIX(1);
4554 else
4555 den = ndigits_denominator(ndigits);
4557 GetTimeval(time, tobj);
4558 v = w2v(rb_time_unmagnify(tobj->timew));
4560 v = modv(v, den);
4561 return time_add(tobj, time, v, -1);
4565 * call-seq:
4566 * ceil(ndigits = 0) -> new_time
4568 * Returns a new +Time+ object whose numerical value
4569 * is greater than or equal to +self+ with its seconds
4570 * truncated to precision +ndigits+:
4572 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4573 * t # => 2010-03-30 05:43:25.123456789 UTC
4574 * t.ceil # => 2010-03-30 05:43:26 UTC
4575 * t.ceil(2) # => 2010-03-30 05:43:25.13 UTC
4576 * t.ceil(4) # => 2010-03-30 05:43:25.1235 UTC
4577 * t.ceil(6) # => 2010-03-30 05:43:25.123457 UTC
4578 * t.ceil(8) # => 2010-03-30 05:43:25.12345679 UTC
4579 * t.ceil(10) # => 2010-03-30 05:43:25.123456789 UTC
4581 * t = Time.utc(1999, 12, 31, 23, 59, 59)
4582 * t # => 1999-12-31 23:59:59 UTC
4583 * (t + 0.4).ceil # => 2000-01-01 00:00:00 UTC
4584 * (t + 0.9).ceil # => 2000-01-01 00:00:00 UTC
4585 * (t + 1.4).ceil # => 2000-01-01 00:00:01 UTC
4586 * (t + 1.9).ceil # => 2000-01-01 00:00:01 UTC
4588 * Related: Time#floor, Time#round.
4591 static VALUE
4592 time_ceil(int argc, VALUE *argv, VALUE time)
4594 VALUE ndigits, v, den;
4595 struct time_object *tobj;
4597 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4598 den = INT2FIX(1);
4599 else
4600 den = ndigits_denominator(ndigits);
4602 GetTimeval(time, tobj);
4603 v = w2v(rb_time_unmagnify(tobj->timew));
4605 v = modv(v, den);
4606 if (!rb_equal(v, INT2FIX(0))) {
4607 v = subv(den, v);
4609 return time_add(tobj, time, v, 1);
4613 * call-seq:
4614 * sec -> integer
4616 * Returns the integer second of the minute for +self+,
4617 * in range (0..60):
4619 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4620 * # => 2000-01-02 03:04:05 +000006
4621 * t.sec # => 5
4623 * Note: the second value may be 60 when there is a
4624 * {leap second}[https://en.wikipedia.org/wiki/Leap_second].
4626 * Related: Time#year, Time#mon, Time#min.
4629 static VALUE
4630 time_sec(VALUE time)
4632 struct time_object *tobj;
4634 GetTimeval(time, tobj);
4635 MAKE_TM(time, tobj);
4636 return INT2FIX(tobj->vtm.sec);
4640 * call-seq:
4641 * min -> integer
4643 * Returns the integer minute of the hour for +self+,
4644 * in range (0..59):
4646 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4647 * # => 2000-01-02 03:04:05 +000006
4648 * t.min # => 4
4650 * Related: Time#year, Time#mon, Time#sec.
4653 static VALUE
4654 time_min(VALUE time)
4656 struct time_object *tobj;
4658 GetTimeval(time, tobj);
4659 MAKE_TM(time, tobj);
4660 return INT2FIX(tobj->vtm.min);
4664 * call-seq:
4665 * hour -> integer
4667 * Returns the integer hour of the day for +self+,
4668 * in range (0..23):
4670 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4671 * # => 2000-01-02 03:04:05 +000006
4672 * t.hour # => 3
4674 * Related: Time#year, Time#mon, Time#min.
4677 static VALUE
4678 time_hour(VALUE time)
4680 struct time_object *tobj;
4682 GetTimeval(time, tobj);
4683 MAKE_TM(time, tobj);
4684 return INT2FIX(tobj->vtm.hour);
4688 * call-seq:
4689 * mday -> integer
4691 * Returns the integer day of the month for +self+,
4692 * in range (1..31):
4694 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4695 * # => 2000-01-02 03:04:05 +000006
4696 * t.mday # => 2
4698 * Related: Time#year, Time#hour, Time#min.
4701 static VALUE
4702 time_mday(VALUE time)
4704 struct time_object *tobj;
4706 GetTimeval(time, tobj);
4707 MAKE_TM(time, tobj);
4708 return INT2FIX(tobj->vtm.mday);
4712 * call-seq:
4713 * mon -> integer
4715 * Returns the integer month of the year for +self+,
4716 * in range (1..12):
4718 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4719 * # => 2000-01-02 03:04:05 +000006
4720 * t.mon # => 1
4722 * Related: Time#year, Time#hour, Time#min.
4725 static VALUE
4726 time_mon(VALUE time)
4728 struct time_object *tobj;
4730 GetTimeval(time, tobj);
4731 MAKE_TM(time, tobj);
4732 return INT2FIX(tobj->vtm.mon);
4736 * call-seq:
4737 * year -> integer
4739 * Returns the integer year for +self+:
4741 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4742 * # => 2000-01-02 03:04:05 +000006
4743 * t.year # => 2000
4745 * Related: Time#mon, Time#hour, Time#min.
4748 static VALUE
4749 time_year(VALUE time)
4751 struct time_object *tobj;
4753 GetTimeval(time, tobj);
4754 MAKE_TM(time, tobj);
4755 return tobj->vtm.year;
4759 * call-seq:
4760 * wday -> integer
4762 * Returns the integer day of the week for +self+,
4763 * in range (0..6), with Sunday as zero.
4765 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4766 * # => 2000-01-02 03:04:05 +000006
4767 * t.wday # => 0
4768 * t.sunday? # => true
4770 * Related: Time#year, Time#hour, Time#min.
4773 static VALUE
4774 time_wday(VALUE time)
4776 struct time_object *tobj;
4778 GetTimeval(time, tobj);
4779 MAKE_TM_ENSURE(time, tobj, tobj->vtm.wday != VTM_WDAY_INITVAL);
4780 return INT2FIX((int)tobj->vtm.wday);
4783 #define wday_p(n) {\
4784 return RBOOL(time_wday(time) == INT2FIX(n)); \
4788 * call-seq:
4789 * sunday? -> true or false
4791 * Returns +true+ if +self+ represents a Sunday, +false+ otherwise:
4793 * t = Time.utc(2000, 1, 2) # => 2000-01-02 00:00:00 UTC
4794 * t.sunday? # => true
4796 * Related: Time#monday?, Time#tuesday?, Time#wednesday?.
4799 static VALUE
4800 time_sunday(VALUE time)
4802 wday_p(0);
4806 * call-seq:
4807 * monday? -> true or false
4809 * Returns +true+ if +self+ represents a Monday, +false+ otherwise:
4811 * t = Time.utc(2000, 1, 3) # => 2000-01-03 00:00:00 UTC
4812 * t.monday? # => true
4814 * Related: Time#tuesday?, Time#wednesday?, Time#thursday?.
4817 static VALUE
4818 time_monday(VALUE time)
4820 wday_p(1);
4824 * call-seq:
4825 * tuesday? -> true or false
4827 * Returns +true+ if +self+ represents a Tuesday, +false+ otherwise:
4829 * t = Time.utc(2000, 1, 4) # => 2000-01-04 00:00:00 UTC
4830 * t.tuesday? # => true
4832 * Related: Time#wednesday?, Time#thursday?, Time#friday?.
4835 static VALUE
4836 time_tuesday(VALUE time)
4838 wday_p(2);
4842 * call-seq:
4843 * wednesday? -> true or false
4845 * Returns +true+ if +self+ represents a Wednesday, +false+ otherwise:
4847 * t = Time.utc(2000, 1, 5) # => 2000-01-05 00:00:00 UTC
4848 * t.wednesday? # => true
4850 * Related: Time#thursday?, Time#friday?, Time#saturday?.
4853 static VALUE
4854 time_wednesday(VALUE time)
4856 wday_p(3);
4860 * call-seq:
4861 * thursday? -> true or false
4863 * Returns +true+ if +self+ represents a Thursday, +false+ otherwise:
4865 * t = Time.utc(2000, 1, 6) # => 2000-01-06 00:00:00 UTC
4866 * t.thursday? # => true
4868 * Related: Time#friday?, Time#saturday?, Time#sunday?.
4871 static VALUE
4872 time_thursday(VALUE time)
4874 wday_p(4);
4878 * call-seq:
4879 * friday? -> true or false
4881 * Returns +true+ if +self+ represents a Friday, +false+ otherwise:
4883 * t = Time.utc(2000, 1, 7) # => 2000-01-07 00:00:00 UTC
4884 * t.friday? # => true
4886 * Related: Time#saturday?, Time#sunday?, Time#monday?.
4889 static VALUE
4890 time_friday(VALUE time)
4892 wday_p(5);
4896 * call-seq:
4897 * saturday? -> true or false
4899 * Returns +true+ if +self+ represents a Saturday, +false+ otherwise:
4901 * t = Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC
4902 * t.saturday? # => true
4904 * Related: Time#sunday?, Time#monday?, Time#tuesday?.
4907 static VALUE
4908 time_saturday(VALUE time)
4910 wday_p(6);
4914 * call-seq:
4915 * yday -> integer
4917 * Returns the integer day of the year of +self+, in range (1..366).
4919 * Time.new(2000, 1, 1).yday # => 1
4920 * Time.new(2000, 12, 31).yday # => 366
4923 static VALUE
4924 time_yday(VALUE time)
4926 struct time_object *tobj;
4928 GetTimeval(time, tobj);
4929 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
4930 return INT2FIX(tobj->vtm.yday);
4934 * call-seq:
4935 * dst? -> true or false
4937 * Returns +true+ if +self+ is in daylight saving time, +false+ otherwise:
4939 * t = Time.local(2000, 1, 1) # => 2000-01-01 00:00:00 -0600
4940 * t.zone # => "Central Standard Time"
4941 * t.dst? # => false
4942 * t = Time.local(2000, 7, 1) # => 2000-07-01 00:00:00 -0500
4943 * t.zone # => "Central Daylight Time"
4944 * t.dst? # => true
4948 static VALUE
4949 time_isdst(VALUE time)
4951 struct time_object *tobj;
4953 GetTimeval(time, tobj);
4954 MAKE_TM(time, tobj);
4955 if (tobj->vtm.isdst == VTM_ISDST_INITVAL) {
4956 rb_raise(rb_eRuntimeError, "isdst is not set yet");
4958 return RBOOL(tobj->vtm.isdst);
4962 * call-seq:
4963 * time.zone -> string or timezone
4965 * Returns the string name of the time zone for +self+:
4967 * Time.utc(2000, 1, 1).zone # => "UTC"
4968 * Time.new(2000, 1, 1).zone # => "Central Standard Time"
4971 static VALUE
4972 time_zone(VALUE time)
4974 struct time_object *tobj;
4975 VALUE zone;
4977 GetTimeval(time, tobj);
4978 MAKE_TM(time, tobj);
4980 if (TZMODE_UTC_P(tobj)) {
4981 return rb_usascii_str_new_cstr("UTC");
4983 zone = tobj->vtm.zone;
4984 if (NIL_P(zone))
4985 return Qnil;
4987 if (RB_TYPE_P(zone, T_STRING))
4988 zone = rb_str_dup(zone);
4989 return zone;
4993 * call-seq:
4994 * utc_offset -> integer
4996 * Returns the offset in seconds between the timezones of UTC and +self+:
4998 * Time.utc(2000, 1, 1).utc_offset # => 0
4999 * Time.local(2000, 1, 1).utc_offset # => -21600 # -6*3600, or minus six hours.
5003 VALUE
5004 rb_time_utc_offset(VALUE time)
5006 struct time_object *tobj;
5008 GetTimeval(time, tobj);
5010 if (TZMODE_UTC_P(tobj)) {
5011 return INT2FIX(0);
5013 else {
5014 MAKE_TM(time, tobj);
5015 return tobj->vtm.utc_offset;
5020 * call-seq:
5021 * to_a -> array
5023 * Returns a 10-element array of values representing +self+:
5025 * Time.utc(2000, 1, 1).to_a
5026 * # => [0, 0, 0, 1, 1, 2000, 6, 1, false, "UTC"]
5027 * # [sec, min, hour, day, mon, year, wday, yday, dst?, zone]
5029 * The returned array is suitable for use as an argument to Time.utc or Time.local
5030 * to create a new +Time+ object.
5034 static VALUE
5035 time_to_a(VALUE time)
5037 struct time_object *tobj;
5039 GetTimeval(time, tobj);
5040 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5041 return rb_ary_new3(10,
5042 INT2FIX(tobj->vtm.sec),
5043 INT2FIX(tobj->vtm.min),
5044 INT2FIX(tobj->vtm.hour),
5045 INT2FIX(tobj->vtm.mday),
5046 INT2FIX(tobj->vtm.mon),
5047 tobj->vtm.year,
5048 INT2FIX(tobj->vtm.wday),
5049 INT2FIX(tobj->vtm.yday),
5050 RBOOL(tobj->vtm.isdst),
5051 time_zone(time));
5055 * call-seq:
5056 * deconstruct_keys(array_of_names_or_nil) -> hash
5058 * Returns a hash of the name/value pairs, to use in pattern matching.
5059 * Possible keys are: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>,
5060 * <tt>:yday</tt>, <tt>:wday</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>,
5061 * <tt>:subsec</tt>, <tt>:dst</tt>, <tt>:zone</tt>.
5063 * Possible usages:
5065 * t = Time.utc(2022, 10, 5, 21, 25, 30)
5067 * if t in wday: 3, day: ..7 # uses deconstruct_keys underneath
5068 * puts "first Wednesday of the month"
5069 * end
5070 * #=> prints "first Wednesday of the month"
5072 * case t
5073 * in year: ...2022
5074 * puts "too old"
5075 * in month: ..9
5076 * puts "quarter 1-3"
5077 * in wday: 1..5, month:
5078 * puts "working day in month #{month}"
5079 * end
5080 * #=> prints "working day in month 10"
5082 * Note that deconstruction by pattern can also be combined with class check:
5084 * if t in Time(wday: 3, day: ..7)
5085 * puts "first Wednesday of the month"
5086 * end
5089 static VALUE
5090 time_deconstruct_keys(VALUE time, VALUE keys)
5092 struct time_object *tobj;
5093 VALUE h;
5094 long i;
5096 GetTimeval(time, tobj);
5097 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5099 if (NIL_P(keys)) {
5100 h = rb_hash_new_with_size(11);
5102 rb_hash_aset(h, sym_year, tobj->vtm.year);
5103 rb_hash_aset(h, sym_month, INT2FIX(tobj->vtm.mon));
5104 rb_hash_aset(h, sym_day, INT2FIX(tobj->vtm.mday));
5105 rb_hash_aset(h, sym_yday, INT2FIX(tobj->vtm.yday));
5106 rb_hash_aset(h, sym_wday, INT2FIX(tobj->vtm.wday));
5107 rb_hash_aset(h, sym_hour, INT2FIX(tobj->vtm.hour));
5108 rb_hash_aset(h, sym_min, INT2FIX(tobj->vtm.min));
5109 rb_hash_aset(h, sym_sec, INT2FIX(tobj->vtm.sec));
5110 rb_hash_aset(h, sym_subsec,
5111 quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
5112 rb_hash_aset(h, sym_dst, RBOOL(tobj->vtm.isdst));
5113 rb_hash_aset(h, sym_zone, time_zone(time));
5115 return h;
5117 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
5118 rb_raise(rb_eTypeError,
5119 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
5120 rb_obj_class(keys));
5124 h = rb_hash_new_with_size(RARRAY_LEN(keys));
5126 for (i=0; i<RARRAY_LEN(keys); i++) {
5127 VALUE key = RARRAY_AREF(keys, i);
5129 if (sym_year == key) rb_hash_aset(h, key, tobj->vtm.year);
5130 if (sym_month == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mon));
5131 if (sym_day == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mday));
5132 if (sym_yday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.yday));
5133 if (sym_wday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.wday));
5134 if (sym_hour == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.hour));
5135 if (sym_min == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.min));
5136 if (sym_sec == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.sec));
5137 if (sym_subsec == key) {
5138 rb_hash_aset(h, key, quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
5140 if (sym_dst == key) rb_hash_aset(h, key, RBOOL(tobj->vtm.isdst));
5141 if (sym_zone == key) rb_hash_aset(h, key, time_zone(time));
5143 return h;
5146 static VALUE
5147 rb_strftime_alloc(const char *format, size_t format_len, rb_encoding *enc,
5148 VALUE time, struct vtm *vtm, wideval_t timew, int gmt)
5150 VALUE timev = Qnil;
5151 struct timespec ts;
5153 if (!timew2timespec_exact(timew, &ts))
5154 timev = w2v(rb_time_unmagnify(timew));
5156 if (NIL_P(timev)) {
5157 return rb_strftime_timespec(format, format_len, enc, time, vtm, &ts, gmt);
5159 else {
5160 return rb_strftime(format, format_len, enc, time, vtm, timev, gmt);
5164 static VALUE
5165 strftime_cstr(const char *fmt, size_t len, VALUE time, rb_encoding *enc)
5167 struct time_object *tobj;
5168 VALUE str;
5170 GetTimeval(time, tobj);
5171 MAKE_TM(time, tobj);
5172 str = rb_strftime_alloc(fmt, len, enc, time, &tobj->vtm, tobj->timew, TZMODE_UTC_P(tobj));
5173 if (!str) rb_raise(rb_eArgError, "invalid format: %s", fmt);
5174 return str;
5178 * call-seq:
5179 * strftime(format_string) -> string
5181 * Returns a string representation of +self+,
5182 * formatted according to the given string +format+.
5183 * See {Formats for Dates and Times}[rdoc-ref:strftime_formatting.rdoc].
5186 static VALUE
5187 time_strftime(VALUE time, VALUE format)
5189 struct time_object *tobj;
5190 const char *fmt;
5191 long len;
5192 rb_encoding *enc;
5193 VALUE tmp;
5195 GetTimeval(time, tobj);
5196 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5197 StringValue(format);
5198 if (!rb_enc_str_asciicompat_p(format)) {
5199 rb_raise(rb_eArgError, "format should have ASCII compatible encoding");
5201 tmp = rb_str_tmp_frozen_acquire(format);
5202 fmt = RSTRING_PTR(tmp);
5203 len = RSTRING_LEN(tmp);
5204 enc = rb_enc_get(format);
5205 if (len == 0) {
5206 rb_warning("strftime called with empty format string");
5207 return rb_enc_str_new(0, 0, enc);
5209 else {
5210 VALUE str = rb_strftime_alloc(fmt, len, enc, time, &tobj->vtm, tobj->timew,
5211 TZMODE_UTC_P(tobj));
5212 rb_str_tmp_frozen_release(format, tmp);
5213 if (!str) rb_raise(rb_eArgError, "invalid format: %"PRIsVALUE, format);
5214 return str;
5218 int ruby_marshal_write_long(long x, char *buf);
5220 enum {base_dump_size = 8};
5222 /* :nodoc: */
5223 static VALUE
5224 time_mdump(VALUE time)
5226 struct time_object *tobj;
5227 unsigned long p, s;
5228 char buf[base_dump_size + sizeof(long) + 1];
5229 int i;
5230 VALUE str;
5232 struct vtm vtm;
5233 long year;
5234 long usec, nsec;
5235 VALUE subsecx, nano, subnano, v, zone;
5237 VALUE year_extend = Qnil;
5238 const int max_year = 1900+0xffff;
5240 GetTimeval(time, tobj);
5242 gmtimew(tobj->timew, &vtm);
5244 if (FIXNUM_P(vtm.year)) {
5245 year = FIX2LONG(vtm.year);
5246 if (year > max_year) {
5247 year_extend = INT2FIX(year - max_year);
5248 year = max_year;
5250 else if (year < 1900) {
5251 year_extend = LONG2NUM(1900 - year);
5252 year = 1900;
5255 else {
5256 if (rb_int_positive_p(vtm.year)) {
5257 year_extend = rb_int_minus(vtm.year, INT2FIX(max_year));
5258 year = max_year;
5260 else {
5261 year_extend = rb_int_minus(INT2FIX(1900), vtm.year);
5262 year = 1900;
5266 subsecx = vtm.subsecx;
5268 nano = mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE));
5269 divmodv(nano, INT2FIX(1), &v, &subnano);
5270 nsec = FIX2LONG(v);
5271 usec = nsec / 1000;
5272 nsec = nsec % 1000;
5274 nano = addv(LONG2FIX(nsec), subnano);
5276 p = 0x1UL << 31 | /* 1 */
5277 TZMODE_UTC_P(tobj) << 30 | /* 1 */
5278 (year-1900) << 14 | /* 16 */
5279 (vtm.mon-1) << 10 | /* 4 */
5280 vtm.mday << 5 | /* 5 */
5281 vtm.hour; /* 5 */
5282 s = (unsigned long)vtm.min << 26 | /* 6 */
5283 vtm.sec << 20 | /* 6 */
5284 usec; /* 20 */
5286 for (i=0; i<4; i++) {
5287 buf[i] = (unsigned char)p;
5288 p = RSHIFT(p, 8);
5290 for (i=4; i<8; i++) {
5291 buf[i] = (unsigned char)s;
5292 s = RSHIFT(s, 8);
5295 if (!NIL_P(year_extend)) {
5297 * Append extended year distance from 1900..(1900+0xffff). In
5298 * each cases, there is no sign as the value is positive. The
5299 * format is length (marshaled long) + little endian packed
5300 * binary (like as Integer).
5302 size_t ysize = rb_absint_size(year_extend, NULL);
5303 char *p, *const buf_year_extend = buf + base_dump_size;
5304 if (ysize > LONG_MAX ||
5305 (i = ruby_marshal_write_long((long)ysize, buf_year_extend)) < 0) {
5306 rb_raise(rb_eArgError, "year too %s to marshal: %"PRIsVALUE" UTC",
5307 (year == 1900 ? "small" : "big"), vtm.year);
5309 i += base_dump_size;
5310 str = rb_str_new(NULL, i + ysize);
5311 p = RSTRING_PTR(str);
5312 memcpy(p, buf, i);
5313 p += i;
5314 rb_integer_pack(year_extend, p, ysize, 1, 0, INTEGER_PACK_LITTLE_ENDIAN);
5316 else {
5317 str = rb_str_new(buf, base_dump_size);
5319 rb_copy_generic_ivar(str, time);
5320 if (!rb_equal(nano, INT2FIX(0))) {
5321 if (RB_TYPE_P(nano, T_RATIONAL)) {
5322 rb_ivar_set(str, id_nano_num, RRATIONAL(nano)->num);
5323 rb_ivar_set(str, id_nano_den, RRATIONAL(nano)->den);
5325 else {
5326 rb_ivar_set(str, id_nano_num, nano);
5327 rb_ivar_set(str, id_nano_den, INT2FIX(1));
5330 if (nsec) { /* submicro is only for Ruby 1.9.1 compatibility */
5332 * submicro is formatted in fixed-point packed BCD (without sign).
5333 * It represent digits under microsecond.
5334 * For nanosecond resolution, 3 digits (2 bytes) are used.
5335 * However it can be longer.
5336 * Extra digits are ignored for loading.
5338 char buf[2];
5339 int len = (int)sizeof(buf);
5340 buf[1] = (char)((nsec % 10) << 4);
5341 nsec /= 10;
5342 buf[0] = (char)(nsec % 10);
5343 nsec /= 10;
5344 buf[0] |= (char)((nsec % 10) << 4);
5345 if (buf[1] == 0)
5346 len = 1;
5347 rb_ivar_set(str, id_submicro, rb_str_new(buf, len));
5349 if (!TZMODE_UTC_P(tobj)) {
5350 VALUE off = rb_time_utc_offset(time), div, mod;
5351 divmodv(off, INT2FIX(1), &div, &mod);
5352 if (rb_equal(mod, INT2FIX(0)))
5353 off = rb_Integer(div);
5354 rb_ivar_set(str, id_offset, off);
5356 zone = tobj->vtm.zone;
5357 if (maybe_tzobj_p(zone)) {
5358 zone = rb_funcallv(zone, id_name, 0, 0);
5360 rb_ivar_set(str, id_zone, zone);
5361 return str;
5364 /* :nodoc: */
5365 static VALUE
5366 time_dump(int argc, VALUE *argv, VALUE time)
5368 VALUE str;
5370 rb_check_arity(argc, 0, 1);
5371 str = time_mdump(time);
5373 return str;
5376 static VALUE
5377 mload_findzone(VALUE arg)
5379 VALUE *argp = (VALUE *)arg;
5380 VALUE time = argp[0], zone = argp[1];
5381 return find_timezone(time, zone);
5384 static VALUE
5385 mload_zone(VALUE time, VALUE zone)
5387 VALUE z, args[2];
5388 args[0] = time;
5389 args[1] = zone;
5390 z = rb_rescue(mload_findzone, (VALUE)args, 0, Qnil);
5391 if (NIL_P(z)) return rb_fstring(zone);
5392 if (RB_TYPE_P(z, T_STRING)) return rb_fstring(z);
5393 return z;
5396 long ruby_marshal_read_long(const char **buf, long len);
5398 /* :nodoc: */
5399 static VALUE
5400 time_mload(VALUE time, VALUE str)
5402 struct time_object *tobj;
5403 unsigned long p, s;
5404 time_t sec;
5405 long usec;
5406 unsigned char *buf;
5407 struct vtm vtm;
5408 int i, gmt;
5409 long nsec;
5410 VALUE submicro, nano_num, nano_den, offset, zone, year;
5411 wideval_t timew;
5413 time_modify(time);
5415 #define get_attr(attr, iffound) \
5416 attr = rb_attr_delete(str, id_##attr); \
5417 if (!NIL_P(attr)) { \
5418 iffound; \
5421 get_attr(nano_num, {});
5422 get_attr(nano_den, {});
5423 get_attr(submicro, {});
5424 get_attr(offset, (offset = rb_rescue(validate_utc_offset, offset, 0, Qnil)));
5425 get_attr(zone, (zone = rb_rescue(validate_zone_name, zone, 0, Qnil)));
5426 get_attr(year, {});
5428 #undef get_attr
5430 rb_copy_generic_ivar(time, str);
5432 StringValue(str);
5433 buf = (unsigned char *)RSTRING_PTR(str);
5434 if (RSTRING_LEN(str) < base_dump_size) {
5435 goto invalid_format;
5438 p = s = 0;
5439 for (i=0; i<4; i++) {
5440 p |= (unsigned long)buf[i]<<(8*i);
5442 for (i=4; i<8; i++) {
5443 s |= (unsigned long)buf[i]<<(8*(i-4));
5446 if ((p & (1UL<<31)) == 0) {
5447 gmt = 0;
5448 offset = Qnil;
5449 sec = p;
5450 usec = s;
5451 nsec = usec * 1000;
5452 timew = wadd(rb_time_magnify(TIMET2WV(sec)), wmulquoll(WINT2FIXWV(usec), TIME_SCALE, 1000000));
5454 else {
5455 p &= ~(1UL<<31);
5456 gmt = (int)((p >> 30) & 0x1);
5458 if (NIL_P(year)) {
5459 year = INT2FIX(((int)(p >> 14) & 0xffff) + 1900);
5461 if (RSTRING_LEN(str) > base_dump_size) {
5462 long len = RSTRING_LEN(str) - base_dump_size;
5463 long ysize = 0;
5464 VALUE year_extend;
5465 const char *ybuf = (const char *)(buf += base_dump_size);
5466 ysize = ruby_marshal_read_long(&ybuf, len);
5467 len -= ybuf - (const char *)buf;
5468 if (ysize < 0 || ysize > len) goto invalid_format;
5469 year_extend = rb_integer_unpack(ybuf, ysize, 1, 0, INTEGER_PACK_LITTLE_ENDIAN);
5470 if (year == INT2FIX(1900)) {
5471 year = rb_int_minus(year, year_extend);
5473 else {
5474 year = rb_int_plus(year, year_extend);
5477 unsigned int mon = ((int)(p >> 10) & 0xf); /* 0...12 */
5478 if (mon >= 12) {
5479 mon -= 12;
5480 year = addv(year, LONG2FIX(1));
5482 vtm.year = year;
5483 vtm.mon = mon + 1;
5484 vtm.mday = (int)(p >> 5) & 0x1f;
5485 vtm.hour = (int) p & 0x1f;
5486 vtm.min = (int)(s >> 26) & 0x3f;
5487 vtm.sec = (int)(s >> 20) & 0x3f;
5488 vtm.utc_offset = INT2FIX(0);
5489 vtm.yday = vtm.wday = 0;
5490 vtm.isdst = 0;
5491 vtm.zone = str_empty;
5493 usec = (long)(s & 0xfffff);
5494 nsec = usec * 1000;
5497 vtm.subsecx = mulquov(LONG2FIX(nsec), INT2FIX(TIME_SCALE), LONG2FIX(1000000000));
5498 if (nano_num != Qnil) {
5499 VALUE nano = quov(num_exact(nano_num), num_exact(nano_den));
5500 vtm.subsecx = addv(vtm.subsecx, mulquov(nano, INT2FIX(TIME_SCALE), LONG2FIX(1000000000)));
5502 else if (submicro != Qnil) { /* for Ruby 1.9.1 compatibility */
5503 unsigned char *ptr;
5504 long len;
5505 int digit;
5506 ptr = (unsigned char*)StringValuePtr(submicro);
5507 len = RSTRING_LEN(submicro);
5508 nsec = 0;
5509 if (0 < len) {
5510 if (10 <= (digit = ptr[0] >> 4)) goto end_submicro;
5511 nsec += digit * 100;
5512 if (10 <= (digit = ptr[0] & 0xf)) goto end_submicro;
5513 nsec += digit * 10;
5515 if (1 < len) {
5516 if (10 <= (digit = ptr[1] >> 4)) goto end_submicro;
5517 nsec += digit;
5519 vtm.subsecx = addv(vtm.subsecx, mulquov(LONG2FIX(nsec), INT2FIX(TIME_SCALE), LONG2FIX(1000000000)));
5520 end_submicro: ;
5522 timew = timegmw(&vtm);
5525 GetNewTimeval(time, tobj);
5526 TZMODE_SET_LOCALTIME(tobj);
5527 tobj->vtm.tm_got = 0;
5528 time_set_timew(time, tobj, timew);
5530 if (gmt) {
5531 TZMODE_SET_UTC(tobj);
5533 else if (!NIL_P(offset)) {
5534 time_set_utc_offset(time, offset);
5535 time_fixoff(time);
5537 if (!NIL_P(zone)) {
5538 zone = mload_zone(time, zone);
5539 tobj->vtm.zone = zone;
5540 zone_localtime(zone, time);
5543 return time;
5545 invalid_format:
5546 rb_raise(rb_eTypeError, "marshaled time format differ");
5547 UNREACHABLE_RETURN(Qundef);
5550 /* :nodoc: */
5551 static VALUE
5552 time_load(VALUE klass, VALUE str)
5554 VALUE time = time_s_alloc(klass);
5556 time_mload(time, str);
5557 return time;
5560 /* :nodoc:*/
5561 /* Document-class: Time::tm
5563 * A container class for timezone conversion.
5567 * call-seq:
5569 * Time::tm.from_time(t) -> tm
5571 * Creates new Time::tm object from a Time object.
5574 static VALUE
5575 tm_from_time(VALUE klass, VALUE time)
5577 struct time_object *tobj;
5578 struct vtm vtm, *v;
5579 VALUE tm;
5580 struct time_object *ttm;
5582 GetTimeval(time, tobj);
5583 tm = time_s_alloc(klass);
5584 ttm = RTYPEDDATA_GET_DATA(tm);
5585 v = &vtm;
5586 GMTIMEW(ttm->timew = tobj->timew, v);
5587 ttm->timew = wsub(ttm->timew, v->subsecx);
5588 v->subsecx = INT2FIX(0);
5589 v->zone = Qnil;
5590 time_set_vtm(tm, ttm, *v);
5592 ttm->vtm.tm_got = 1;
5593 TZMODE_SET_UTC(ttm);
5594 return tm;
5598 * call-seq:
5600 * Time::tm.new(year, month=nil, day=nil, hour=nil, min=nil, sec=nil, zone=nil) -> tm
5602 * Creates new Time::tm object.
5605 static VALUE
5606 tm_initialize(int argc, VALUE *argv, VALUE time)
5608 struct vtm vtm;
5609 wideval_t t;
5611 if (rb_check_arity(argc, 1, 7) > 6) argc = 6;
5612 time_arg(argc, argv, &vtm);
5613 t = timegmw(&vtm);
5614 struct time_object *tobj = RTYPEDDATA_GET_DATA(time);
5615 TZMODE_SET_UTC(tobj);
5616 time_set_timew(time, tobj, t);
5617 time_set_vtm(time, tobj, vtm);
5619 return time;
5622 /* call-seq:
5624 * tm.to_time -> time
5626 * Returns a new Time object.
5629 static VALUE
5630 tm_to_time(VALUE tm)
5632 struct time_object *torig = get_timeval(tm);
5633 VALUE dup = time_s_alloc(rb_cTime);
5634 struct time_object *tobj = RTYPEDDATA_GET_DATA(dup);
5635 *tobj = *torig;
5636 return dup;
5639 static VALUE
5640 tm_plus(VALUE tm, VALUE offset)
5642 return time_add0(rb_obj_class(tm), get_timeval(tm), tm, offset, +1);
5645 static VALUE
5646 tm_minus(VALUE tm, VALUE offset)
5648 return time_add0(rb_obj_class(tm), get_timeval(tm), tm, offset, -1);
5651 static VALUE
5652 Init_tm(VALUE outer, const char *name)
5654 /* :stopdoc:*/
5655 VALUE tm;
5656 tm = rb_define_class_under(outer, name, rb_cObject);
5657 rb_define_alloc_func(tm, time_s_alloc);
5658 rb_define_method(tm, "sec", time_sec, 0);
5659 rb_define_method(tm, "min", time_min, 0);
5660 rb_define_method(tm, "hour", time_hour, 0);
5661 rb_define_method(tm, "mday", time_mday, 0);
5662 rb_define_method(tm, "day", time_mday, 0);
5663 rb_define_method(tm, "mon", time_mon, 0);
5664 rb_define_method(tm, "month", time_mon, 0);
5665 rb_define_method(tm, "year", time_year, 0);
5666 rb_define_method(tm, "isdst", time_isdst, 0);
5667 rb_define_method(tm, "dst?", time_isdst, 0);
5668 rb_define_method(tm, "zone", time_zone, 0);
5669 rb_define_method(tm, "gmtoff", rb_time_utc_offset, 0);
5670 rb_define_method(tm, "gmt_offset", rb_time_utc_offset, 0);
5671 rb_define_method(tm, "utc_offset", rb_time_utc_offset, 0);
5672 rb_define_method(tm, "utc?", time_utc_p, 0);
5673 rb_define_method(tm, "gmt?", time_utc_p, 0);
5674 rb_define_method(tm, "to_s", time_to_s, 0);
5675 rb_define_method(tm, "inspect", time_inspect, 0);
5676 rb_define_method(tm, "to_a", time_to_a, 0);
5677 rb_define_method(tm, "tv_sec", time_to_i, 0);
5678 rb_define_method(tm, "tv_usec", time_usec, 0);
5679 rb_define_method(tm, "usec", time_usec, 0);
5680 rb_define_method(tm, "tv_nsec", time_nsec, 0);
5681 rb_define_method(tm, "nsec", time_nsec, 0);
5682 rb_define_method(tm, "subsec", time_subsec, 0);
5683 rb_define_method(tm, "to_i", time_to_i, 0);
5684 rb_define_method(tm, "to_f", time_to_f, 0);
5685 rb_define_method(tm, "to_r", time_to_r, 0);
5686 rb_define_method(tm, "+", tm_plus, 1);
5687 rb_define_method(tm, "-", tm_minus, 1);
5688 rb_define_method(tm, "initialize", tm_initialize, -1);
5689 rb_define_method(tm, "utc", tm_to_time, 0);
5690 rb_alias(tm, rb_intern_const("to_time"), rb_intern_const("utc"));
5691 rb_define_singleton_method(tm, "from_time", tm_from_time, 1);
5692 /* :startdoc:*/
5694 return tm;
5697 VALUE
5698 rb_time_zone_abbreviation(VALUE zone, VALUE time)
5700 VALUE tm, abbr, strftime_args[2];
5702 abbr = rb_check_string_type(zone);
5703 if (!NIL_P(abbr)) return abbr;
5705 tm = tm_from_time(rb_cTimeTM, time);
5706 abbr = rb_check_funcall(zone, rb_intern("abbr"), 1, &tm);
5707 if (!UNDEF_P(abbr)) {
5708 goto found;
5710 #ifdef SUPPORT_TZINFO_ZONE_ABBREVIATION
5711 abbr = rb_check_funcall(zone, rb_intern("period_for_utc"), 1, &tm);
5712 if (!UNDEF_P(abbr)) {
5713 abbr = rb_funcallv(abbr, rb_intern("abbreviation"), 0, 0);
5714 goto found;
5716 #endif
5717 strftime_args[0] = rb_fstring_lit("%Z");
5718 strftime_args[1] = tm;
5719 abbr = rb_check_funcall(zone, rb_intern("strftime"), 2, strftime_args);
5720 if (!UNDEF_P(abbr)) {
5721 goto found;
5723 abbr = rb_check_funcall_default(zone, idName, 0, 0, Qnil);
5724 found:
5725 return rb_obj_as_string(abbr);
5728 /* Internal Details:
5730 * Since Ruby 1.9.2, Time implementation uses a signed 63 bit integer or
5731 * Integer(T_BIGNUM), Rational.
5732 * The integer is a number of nanoseconds since the _Epoch_ which can
5733 * represent 1823-11-12 to 2116-02-20.
5734 * When Integer(T_BIGNUM) or Rational is used (before 1823, after 2116, under
5735 * nanosecond), Time works slower than when integer is used.
5739 void
5740 Init_Time(void)
5742 id_submicro = rb_intern_const("submicro");
5743 id_nano_num = rb_intern_const("nano_num");
5744 id_nano_den = rb_intern_const("nano_den");
5745 id_offset = rb_intern_const("offset");
5746 id_zone = rb_intern_const("zone");
5747 id_nanosecond = rb_intern_const("nanosecond");
5748 id_microsecond = rb_intern_const("microsecond");
5749 id_millisecond = rb_intern_const("millisecond");
5750 id_nsec = rb_intern_const("nsec");
5751 id_usec = rb_intern_const("usec");
5752 id_local_to_utc = rb_intern_const("local_to_utc");
5753 id_utc_to_local = rb_intern_const("utc_to_local");
5754 id_year = rb_intern_const("year");
5755 id_mon = rb_intern_const("mon");
5756 id_mday = rb_intern_const("mday");
5757 id_hour = rb_intern_const("hour");
5758 id_min = rb_intern_const("min");
5759 id_sec = rb_intern_const("sec");
5760 id_isdst = rb_intern_const("isdst");
5761 id_find_timezone = rb_intern_const("find_timezone");
5763 sym_year = ID2SYM(rb_intern_const("year"));
5764 sym_month = ID2SYM(rb_intern_const("month"));
5765 sym_yday = ID2SYM(rb_intern_const("yday"));
5766 sym_wday = ID2SYM(rb_intern_const("wday"));
5767 sym_day = ID2SYM(rb_intern_const("day"));
5768 sym_hour = ID2SYM(rb_intern_const("hour"));
5769 sym_min = ID2SYM(rb_intern_const("min"));
5770 sym_sec = ID2SYM(rb_intern_const("sec"));
5771 sym_subsec = ID2SYM(rb_intern_const("subsec"));
5772 sym_dst = ID2SYM(rb_intern_const("dst"));
5773 sym_zone = ID2SYM(rb_intern_const("zone"));
5775 str_utc = rb_fstring_lit("UTC");
5776 rb_vm_register_global_object(str_utc);
5777 str_empty = rb_fstring_lit("");
5778 rb_vm_register_global_object(str_empty);
5780 rb_cTime = rb_define_class("Time", rb_cObject);
5781 VALUE scTime = rb_singleton_class(rb_cTime);
5782 rb_include_module(rb_cTime, rb_mComparable);
5784 rb_define_alloc_func(rb_cTime, time_s_alloc);
5785 rb_define_singleton_method(rb_cTime, "utc", time_s_mkutc, -1);
5786 rb_define_singleton_method(rb_cTime, "local", time_s_mktime, -1);
5787 rb_define_alias(scTime, "gm", "utc");
5788 rb_define_alias(scTime, "mktime", "local");
5790 rb_define_method(rb_cTime, "to_i", time_to_i, 0);
5791 rb_define_method(rb_cTime, "to_f", time_to_f, 0);
5792 rb_define_method(rb_cTime, "to_r", time_to_r, 0);
5793 rb_define_method(rb_cTime, "<=>", time_cmp, 1);
5794 rb_define_method(rb_cTime, "eql?", time_eql, 1);
5795 rb_define_method(rb_cTime, "hash", time_hash, 0);
5796 rb_define_method(rb_cTime, "initialize_copy", time_init_copy, 1);
5798 rb_define_method(rb_cTime, "localtime", time_localtime_m, -1);
5799 rb_define_method(rb_cTime, "gmtime", time_gmtime, 0);
5800 rb_define_method(rb_cTime, "utc", time_gmtime, 0);
5801 rb_define_method(rb_cTime, "getlocal", time_getlocaltime, -1);
5802 rb_define_method(rb_cTime, "getgm", time_getgmtime, 0);
5803 rb_define_method(rb_cTime, "getutc", time_getgmtime, 0);
5805 rb_define_method(rb_cTime, "ctime", time_asctime, 0);
5806 rb_define_method(rb_cTime, "asctime", time_asctime, 0);
5807 rb_define_method(rb_cTime, "to_s", time_to_s, 0);
5808 rb_define_method(rb_cTime, "inspect", time_inspect, 0);
5809 rb_define_method(rb_cTime, "to_a", time_to_a, 0);
5810 rb_define_method(rb_cTime, "deconstruct_keys", time_deconstruct_keys, 1);
5812 rb_define_method(rb_cTime, "+", time_plus, 1);
5813 rb_define_method(rb_cTime, "-", time_minus, 1);
5815 rb_define_method(rb_cTime, "round", time_round, -1);
5816 rb_define_method(rb_cTime, "floor", time_floor, -1);
5817 rb_define_method(rb_cTime, "ceil", time_ceil, -1);
5819 rb_define_method(rb_cTime, "sec", time_sec, 0);
5820 rb_define_method(rb_cTime, "min", time_min, 0);
5821 rb_define_method(rb_cTime, "hour", time_hour, 0);
5822 rb_define_method(rb_cTime, "mday", time_mday, 0);
5823 rb_define_method(rb_cTime, "day", time_mday, 0);
5824 rb_define_method(rb_cTime, "mon", time_mon, 0);
5825 rb_define_method(rb_cTime, "month", time_mon, 0);
5826 rb_define_method(rb_cTime, "year", time_year, 0);
5827 rb_define_method(rb_cTime, "wday", time_wday, 0);
5828 rb_define_method(rb_cTime, "yday", time_yday, 0);
5829 rb_define_method(rb_cTime, "isdst", time_isdst, 0);
5830 rb_define_method(rb_cTime, "dst?", time_isdst, 0);
5831 rb_define_method(rb_cTime, "zone", time_zone, 0);
5832 rb_define_method(rb_cTime, "gmtoff", rb_time_utc_offset, 0);
5833 rb_define_method(rb_cTime, "gmt_offset", rb_time_utc_offset, 0);
5834 rb_define_method(rb_cTime, "utc_offset", rb_time_utc_offset, 0);
5836 rb_define_method(rb_cTime, "utc?", time_utc_p, 0);
5837 rb_define_method(rb_cTime, "gmt?", time_utc_p, 0);
5839 rb_define_method(rb_cTime, "sunday?", time_sunday, 0);
5840 rb_define_method(rb_cTime, "monday?", time_monday, 0);
5841 rb_define_method(rb_cTime, "tuesday?", time_tuesday, 0);
5842 rb_define_method(rb_cTime, "wednesday?", time_wednesday, 0);
5843 rb_define_method(rb_cTime, "thursday?", time_thursday, 0);
5844 rb_define_method(rb_cTime, "friday?", time_friday, 0);
5845 rb_define_method(rb_cTime, "saturday?", time_saturday, 0);
5847 rb_define_method(rb_cTime, "tv_sec", time_to_i, 0);
5848 rb_define_method(rb_cTime, "tv_usec", time_usec, 0);
5849 rb_define_method(rb_cTime, "usec", time_usec, 0);
5850 rb_define_method(rb_cTime, "tv_nsec", time_nsec, 0);
5851 rb_define_method(rb_cTime, "nsec", time_nsec, 0);
5852 rb_define_method(rb_cTime, "subsec", time_subsec, 0);
5854 rb_define_method(rb_cTime, "strftime", time_strftime, 1);
5856 /* methods for marshaling */
5857 rb_define_private_method(rb_cTime, "_dump", time_dump, -1);
5858 rb_define_private_method(scTime, "_load", time_load, 1);
5860 if (debug_find_time_numguess) {
5861 rb_define_hooked_variable("$find_time_numguess", (VALUE *)&find_time_numguess,
5862 find_time_numguess_getter, 0);
5865 rb_cTimeTM = Init_tm(rb_cTime, "tm");
5868 #include "timev.rbinc"