首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

DateTime

Parent:Date

DateTime

Date轻松处理日期,小时,分钟,秒和偏移量的子类。

DateTime不考虑任何闰秒,不追踪任何夏令时规则。

DateTime对象是使用::new, ::jd, ::ordinal, ::commercial, ::parse, ::strptime, ::now, Time#to_datetime0等创建的。

代码语言:javascript
复制
require 'date'

DateTime.new(2001,2,3,4,5,6)
                    #=> #<DateTime: 2001-02-03T04:05:06+00:00 ...>

日,时,分或秒的最后一个元素可以是分数。分数的精度假定在最大纳秒。

代码语言:javascript
复制
DateTime.new(2001,2,3.5)
                    #=> #<DateTime: 2001-02-03T12:00:00+00:00 ...>

可选参数偏移量表示本地时间与UTC之间的差异。例如,Rational(3,24)表示UTC的3小时之前,代表UTC Rational(-5,24)的5小时之后。偏移应该是-1到+1,并且其精度假定在最多秒。默认值是零(等于UTC)。

代码语言:javascript
复制
DateTime.new(2001,2,3,4,5,6,Rational(3,24))
                    #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>

偏移量也接受字符串形式:

代码语言:javascript
复制
DateTime.new(2001,2,3,4,5,6,'+03:00')
                    #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>

可选参数是日历改革日期(start),表示Julian日数,应该是2298874到2426355或负/正无限。默认值是Date::ITALY(2299161 = 1582-10-15)。

DateTime对象具有各种方法。查看每个参考。

代码语言:javascript
复制
d = DateTime.parse('3rd Feb 2001 04:05:06+03:30')
                    #=> #<DateTime: 2001-02-03T04:05:06+03:30 ...>
d.hour              #=> 4
d.min               #=> 5
d.sec               #=> 6
d.offset            #=> (7/48)
d.zone              #=> "+03:30"
d += Rational('1.5')
                    #=> #<DateTime: 2001-02-04%16:05:06+03:30 ...>
d = d.new_offset('+09:00')
                    #=> #<DateTime: 2001-02-04%21:35:06+09:00 ...>
d.strftime('%I:%M:%S %p')
                    #=> "09:35:06 PM"
d > DateTime.new(1999)
                    #=> true

什么时候应该使用DateTime,什么时候应该使用Time?

威廉莎士比亚米格尔·德·塞万提斯在历史的同一天去世是一种常见的误解- 因此,联合国教科文组织将4月23 命名为世界读书日,因为这一事实。然而,因为英格兰还没有采用格里历日历改革(直到1752年它们的死亡实际上是相隔10天),由于Ruby的时间类实施了一个格雷戈里日历并且没有日历改革的概念,所以没有办法表达这一点与时间对象。这是DateTime步入的地方:

代码语言:javascript
复制
shakespeare = DateTime.iso8601('1616-04-23', Date::ENGLAND)
 #=> Tue, 23 Apr 1616 00:00:00 +0000
cervantes = DateTime.iso8601('1616-04-23', Date::ITALY)
 #=> Sat, 23 Apr 1616 00:00:00 +0000

已经可以看到一些奇怪的事情 - 一周中的日子不同。进一步考虑:

代码语言:javascript
复制
cervantes == shakespeare
 #=> false
(shakespeare - cervantes).to_i
 #=> 10

这表明实际上他们相隔10天(事实上在塞万提斯死于前一天但在23日被埋葬的11天内)。我们可以通过使用格里高利的方法将莎士比亚的死亡日期转换为死亡日期:

代码语言:javascript
复制
shakespeare.gregorian
 #=> Tue, 03 May 1616 00:00:00 +0000

所以有一种说法认为,4月23日在埃文河畔斯特拉特福举行的所有庆祝活动实际上是自英格兰现在使用公历以来的错误日期。你可以看到为什么当我们跨越改革日期的界限时:

代码语言:javascript
复制
# start off with the anniversary of Shakespeare's birth in 1751
shakespeare = DateTime.iso8601('1751-04-23', Date::ENGLAND)
 #=> Tue, 23 Apr 1751 00:00:00 +0000

# add 366 days since 1752 is a leap year and April 23 is after February 29
shakespeare + 366
 #=> Thu, 23 Apr 1752 00:00:00 +0000

# add another 365 days to take us to the anniversary in 1753
shakespeare + 366 + 365
 #=> Fri, 04 May 1753 00:00:00 +0000

正如你所看到的,如果我们准确地追踪莎士比亚诞辰日后的太阳年数,那么正确的周年日将是5月4日而不是4月23日。

那么你什么时候应该在Ruby中使用DateTime,什么时候应该使用Time?几乎可以肯定的是,你会想使用Time,因为你的应用可能会处理当前的日期和时间。但是,如果您需要在历史背景下处理日期和时间,则您需要使用DateTime来避免犯与联合国教科文组织相同的错误。如果您还必须处理时区,那么最好运气 - 请记住,您可能会处理当地的太阳时间,因为直到19世纪,引入铁路才需要标准时间并最终时区。

公共分类方法

_strptime(string, format='%FT%T%z') → hash Show source

用给定的模板解析给定的日期和时间表示,并返回经过分析的元素的散列。_strptime不支持与strftime不同的标志和宽度的规范。

另见strptime(3)和strftime。

代码语言:javascript
复制
static VALUE
datetime_s__strptime(int argc, VALUE *argv, VALUE klass)
{
    return date_s__strptime_internal(argc, argv, klass, "%FT%T%z");
}

civil([year=-4712[, month=1[, mday=1[, hour=0[, minute=0[, second=0[, offset=0, start=Date::ITALY]]]]]]]) → datetime 显示来源

创建一个表示给定日历日期的DateTime对象。

代码语言:javascript
复制
DateTime.new(2001,2,3)    #=> #<DateTime: 2001-02-03T00:00:00+00:00 ...>
DateTime.new(2001,2,3,4,5,6,'+7')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.new(2001,-11,-26,-20,-55,-54,'+7')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_civil(int argc, VALUE *argv, VALUE klass)
{
    VALUE vy, vm, vd, vh, vmin, vs, vof, vsg, y, fr, fr2, ret;
    int m, d, h, min, s, rof;
    double sg;

    rb_scan_args(argc, argv, "08", &vy, &vm, &vd, &vh, &vmin, &vs, &vof, &vsg);

    y = INT2FIX(-4712);
    m = 1;
    d = 1;

    h = min = s = 0;
    fr2 = INT2FIX(0);
    rof = 0;
    sg = DEFAULT_SG;

    switch (argc) {
      case 8:
        val2sg(vsg, sg);
      case 7:
        val2off(vof, rof);
      case 6:
        num2int_with_frac(s, positive_inf);
      case 5:
        num2int_with_frac(min, 5);
      case 4:
        num2int_with_frac(h, 4);
      case 3:
        num2int_with_frac(d, 3);
      case 2:
        m = NUM2INT(vm);
      case 1:
        y = vy;
    }

    if (guess_style(y, sg) < 0) {
        VALUE nth;
        int ry, rm, rd, rh, rmin, rs;

        if (!valid_gregorian_p(y, m, d,
                               &nth, &ry,
                               &rm, &rd))
            rb_raise(rb_eArgError, "invalid date");
        if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs))
            rb_raise(rb_eArgError, "invalid date");
        canon24oc();

        ret = d_complex_new_internal(klass,
                                     nth, 0,
                                     0, INT2FIX(0),
                                     rof, sg,
                                     ry, rm, rd,
                                     rh, rmin, rs,
                                     HAVE_CIVIL | HAVE_TIME);
    }
    else {
        VALUE nth;
        int ry, rm, rd, rh, rmin, rs, rjd, rjd2, ns;

        if (!valid_civil_p(y, m, d, sg,
                           &nth, &ry,
                           &rm, &rd, &rjd,
                           &ns))
            rb_raise(rb_eArgError, "invalid date");
        if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs))
            rb_raise(rb_eArgError, "invalid date");
        canon24oc();

        rjd2 = jd_local_to_utc(rjd,
                               time_to_df(rh, rmin, rs),
                               rof);

        ret = d_complex_new_internal(klass,
                                     nth, rjd2,
                                     0, INT2FIX(0),
                                     rof, sg,
                                     ry, rm, rd,
                                     rh, rmin, rs,
                                     HAVE_JD | HAVE_CIVIL | HAVE_TIME);
    }
    add_frac();
    return ret;
}

commercial([cwyear=-4712[, cweek=1[, cwday=1[, hour=0[, minute=0[, second=0[, offset=0, start=Date::ITALY]]]]]]]) → datetime Show source

创建一个表示给定星期日期的DateTime对象。

代码语言:javascript
复制
DateTime.commercial(2001) #=> #<DateTime: 2001-01-01T00:00:00+00:00 ...>
DateTime.commercial(2002) #=> #<DateTime: 2001-12-31T00:00:00+00:00 ...>
DateTime.commercial(2001,5,6,4,5,6,'+7')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_commercial(int argc, VALUE *argv, VALUE klass)
{
    VALUE vy, vw, vd, vh, vmin, vs, vof, vsg, y, fr, fr2, ret;
    int w, d, h, min, s, rof;
    double sg;

    rb_scan_args(argc, argv, "08", &vy, &vw, &vd, &vh, &vmin, &vs, &vof, &vsg);

    y = INT2FIX(-4712);
    w = 1;
    d = 1;

    h = min = s = 0;
    fr2 = INT2FIX(0);
    rof = 0;
    sg = DEFAULT_SG;

    switch (argc) {
      case 8:
        val2sg(vsg, sg);
      case 7:
        val2off(vof, rof);
      case 6:
        num2int_with_frac(s, positive_inf);
      case 5:
        num2int_with_frac(min, 5);
      case 4:
        num2int_with_frac(h, 4);
      case 3:
        num2int_with_frac(d, 3);
      case 2:
        w = NUM2INT(vw);
      case 1:
        y = vy;
    }

    {
        VALUE nth;
        int ry, rw, rd, rh, rmin, rs, rjd, rjd2, ns;

        if (!valid_commercial_p(y, w, d, sg,
                                &nth, &ry,
                                &rw, &rd, &rjd,
                                &ns))
            rb_raise(rb_eArgError, "invalid date");
        if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs))
            rb_raise(rb_eArgError, "invalid date");
        canon24oc();

        rjd2 = jd_local_to_utc(rjd,
                               time_to_df(rh, rmin, rs),
                               rof);

        ret = d_complex_new_internal(klass,
                                     nth, rjd2,
                                     0, INT2FIX(0),
                                     rof, sg,
                                     0, 0, 0,
                                     rh, rmin, rs,
                                     HAVE_JD | HAVE_TIME);
    }
    add_frac();
    return ret;
}

httpdate(string='Mon, 01 Jan -4712 00:00:00 GMT', start=Date::ITALY) → datetime Show source

根据某些RFC 2616格式通过解析字符串来创建新的DateTime对象。

代码语言:javascript
复制
DateTime.httpdate('Sat, 03 Feb 2001 04:05:06 GMT')
                          #=> #<DateTime: 2001-02-03T04:05:06+00:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_httpdate(int argc, VALUE *argv, VALUE klass)
{
    VALUE str, sg;

    rb_scan_args(argc, argv, "02", &str, &sg);

    switch (argc) {
      case 0:
        str = rb_str_new2("Mon, 01 Jan -4712 00:00:00 GMT");
      case 1:
        sg = INT2FIX(DEFAULT_SG);
    }

    {
        VALUE hash = date_s__httpdate(klass, str);
        return dt_new_by_frags(klass, hash, sg);
    }
}

iso8601(string='-4712-01-01T00:00:00+00:00', start=Date::ITALY) → datetime Show source

根据某些典型的ISO 8601格式通过解析字符串来创建新的DateTime对象。

代码语言:javascript
复制
DateTime.iso8601('2001-02-03T04:05:06+07:00')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.iso8601('20010203T040506+0700')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.iso8601('2001-W05-6T04:05:06+07:00')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_iso8601(int argc, VALUE *argv, VALUE klass)
{
    VALUE str, sg;

    rb_scan_args(argc, argv, "02", &str, &sg);

    switch (argc) {
      case 0:
        str = rb_str_new2("-4712-01-01T00:00:00+00:00");
      case 1:
        sg = INT2FIX(DEFAULT_SG);
    }

    {
        VALUE hash = date_s__iso8601(klass, str);
        return dt_new_by_frags(klass, hash, sg);
    }
}

jd([jd=0[, hour=0[, minute=0[, second=0[, offset=0, start=Date::ITALY]]]]]) → datetime Show source

创建一个DateTime对象,表示给定的按时间顺序排列的Julian天数。

代码语言:javascript
复制
DateTime.jd(2451944)      #=> #<DateTime: 2001-02-03T00:00:00+00:00 ...>
DateTime.jd(2451945)      #=> #<DateTime: 2001-02-04T00:00:00+00:00 ...>
DateTime.jd(Rational('0.5'))
                          #=> #<DateTime: -4712-01-01T12:00:00+00:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_jd(int argc, VALUE *argv, VALUE klass)
{
    VALUE vjd, vh, vmin, vs, vof, vsg, jd, fr, fr2, ret;
    int h, min, s, rof;
    double sg;

    rb_scan_args(argc, argv, "06", &vjd, &vh, &vmin, &vs, &vof, &vsg);

    jd = INT2FIX(0);

    h = min = s = 0;
    fr2 = INT2FIX(0);
    rof = 0;
    sg = DEFAULT_SG;

    switch (argc) {
      case 6:
        val2sg(vsg, sg);
      case 5:
        val2off(vof, rof);
      case 4:
        num2int_with_frac(s, positive_inf);
      case 3:
        num2int_with_frac(min, 3);
      case 2:
        num2int_with_frac(h, 2);
      case 1:
        num2num_with_frac(jd, 1);
    }

    {
        VALUE nth;
        int rh, rmin, rs, rjd, rjd2;

        if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs))
            rb_raise(rb_eArgError, "invalid date");
        canon24oc();

        decode_jd(jd, &nth, &rjd);
        rjd2 = jd_local_to_utc(rjd,
                               time_to_df(rh, rmin, rs),
                               rof);

        ret = d_complex_new_internal(klass,
                                     nth, rjd2,
                                     0, INT2FIX(0),
                                     rof, sg,
                                     0, 0, 0,
                                     rh, rmin, rs,
                                     HAVE_JD | HAVE_TIME);
    }
    add_frac();
    return ret;
}

jisx0301(string='-4712-01-01T00:00:00+00:00', start=Date::ITALY) → datetime Show source

根据某些典型的JIS X 0301格式,通过解析字符串来创建新的DateTime对象。

代码语言:javascript
复制
DateTime.jisx0301('H13.02.03T04:05:06+07:00')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_jisx0301(int argc, VALUE *argv, VALUE klass)
{
    VALUE str, sg;

    rb_scan_args(argc, argv, "02", &str, &sg);

    switch (argc) {
      case 0:
        str = rb_str_new2("-4712-01-01T00:00:00+00:00");
      case 1:
        sg = INT2FIX(DEFAULT_SG);
    }

    {
        VALUE hash = date_s__jisx0301(klass, str);
        return dt_new_by_frags(klass, hash, sg);
    }
}

json_create(object) Show source

将年y,月m,日d,小时H,分钟M,秒S,偏移量of和日历sg重组日期转换为日期时间,反序列化JSON字符串。

代码语言:javascript
复制
# File ext/json/lib/json/add/date_time.rb, line 12
def self.json_create(object)
  args = object.values_at('y', 'm', 'd', 'H', 'M', 'S')
  of_a, of_b = object['of'].split('/')
  if of_b and of_b != '0'
    args << Rational(of_a.to_i, of_b.to_i)
  else
    args << of_a
  end
  args << object['sg']
  civil(*args)
end

new([year=-4712[, month=1[, mday=1[, hour=0[, minute=0[, second=0[, offset=0, start=Date::ITALY]]]]]]]) → datetime Show source

创建一个表示给定日历日期的DateTime对象。

代码语言:javascript
复制
DateTime.new(2001,2,3)    #=> #<DateTime: 2001-02-03T00:00:00+00:00 ...>
DateTime.new(2001,2,3,4,5,6,'+7')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.new(2001,-11,-26,-20,-55,-54,'+7')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_civil(int argc, VALUE *argv, VALUE klass)
{
    VALUE vy, vm, vd, vh, vmin, vs, vof, vsg, y, fr, fr2, ret;
    int m, d, h, min, s, rof;
    double sg;

    rb_scan_args(argc, argv, "08", &vy, &vm, &vd, &vh, &vmin, &vs, &vof, &vsg);

    y = INT2FIX(-4712);
    m = 1;
    d = 1;

    h = min = s = 0;
    fr2 = INT2FIX(0);
    rof = 0;
    sg = DEFAULT_SG;

    switch (argc) {
      case 8:
        val2sg(vsg, sg);
      case 7:
        val2off(vof, rof);
      case 6:
        num2int_with_frac(s, positive_inf);
      case 5:
        num2int_with_frac(min, 5);
      case 4:
        num2int_with_frac(h, 4);
      case 3:
        num2int_with_frac(d, 3);
      case 2:
        m = NUM2INT(vm);
      case 1:
        y = vy;
    }

    if (guess_style(y, sg) < 0) {
        VALUE nth;
        int ry, rm, rd, rh, rmin, rs;

        if (!valid_gregorian_p(y, m, d,
                               &nth, &ry,
                               &rm, &rd))
            rb_raise(rb_eArgError, "invalid date");
        if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs))
            rb_raise(rb_eArgError, "invalid date");
        canon24oc();

        ret = d_complex_new_internal(klass,
                                     nth, 0,
                                     0, INT2FIX(0),
                                     rof, sg,
                                     ry, rm, rd,
                                     rh, rmin, rs,
                                     HAVE_CIVIL | HAVE_TIME);
    }
    else {
        VALUE nth;
        int ry, rm, rd, rh, rmin, rs, rjd, rjd2, ns;

        if (!valid_civil_p(y, m, d, sg,
                           &nth, &ry,
                           &rm, &rd, &rjd,
                           &ns))
            rb_raise(rb_eArgError, "invalid date");
        if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs))
            rb_raise(rb_eArgError, "invalid date");
        canon24oc();

        rjd2 = jd_local_to_utc(rjd,
                               time_to_df(rh, rmin, rs),
                               rof);

        ret = d_complex_new_internal(klass,
                                     nth, rjd2,
                                     0, INT2FIX(0),
                                     rof, sg,
                                     ry, rm, rd,
                                     rh, rmin, rs,
                                     HAVE_JD | HAVE_CIVIL | HAVE_TIME);
    }
    add_frac();
    return ret;
}

now(start=Date::ITALY) → datetime Show source

创建表示当前时间的DateTime对象。

代码语言:javascript
复制
DateTime.now              #=> #<DateTime: 2011-06-11T21:20:44+09:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_now(int argc, VALUE *argv, VALUE klass)
{
    VALUE vsg, nth, ret;
    double sg;
#ifdef HAVE_CLOCK_GETTIME
    struct timespec ts;
#else
    struct timeval tv;
#endif
    time_t sec;
    struct tm tm;
    long sf, of;
    int y, ry, m, d, h, min, s;

    rb_scan_args(argc, argv, "01", &vsg);

    if (argc < 1)
        sg = DEFAULT_SG;
    else
        sg = NUM2DBL(vsg);

#ifdef HAVE_CLOCK_GETTIME
    if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
        rb_sys_fail("clock_gettime");
    sec = ts.tv_sec;
#else
    if (gettimeofday(&tv, NULL) == -1)
        rb_sys_fail("gettimeofday");
    sec = tv.tv_sec;
#endif
    tzset();
    if (!localtime_r(&sec, &tm))
        rb_sys_fail("localtime");

    y = tm.tm_year + 1900;
    m = tm.tm_mon + 1;
    d = tm.tm_mday;
    h = tm.tm_hour;
    min = tm.tm_min;
    s = tm.tm_sec;
    if (s == 60)
        s = 59;
#ifdef HAVE_STRUCT_TM_TM_GMTOFF
    of = tm.tm_gmtoff;
#elif defined(HAVE_VAR_TIMEZONE)
#ifdef HAVE_VAR_ALTZONE
    of = (long)-((tm.tm_isdst > 0) ? altzone : timezone);
#else
    of = (long)-timezone;
    if (tm.tm_isdst) {
        time_t sec2;

        tm.tm_isdst = 0;
        sec2 = mktime(&tm);
        of += (long)difftime(sec2, sec);
    }
#endif
#elif defined(HAVE_TIMEGM)
    {
        time_t sec2;

        sec2 = timegm(&tm);
        of = (long)difftime(sec2, sec);
    }
#else
    {
        struct tm tm2;
        time_t sec2;

        if (!gmtime_r(&sec, &tm2))
            rb_sys_fail("gmtime");
        tm2.tm_isdst = tm.tm_isdst;
        sec2 = mktime(&tm2);
        of = (long)difftime(sec, sec2);
    }
#endif
#ifdef HAVE_CLOCK_GETTIME
    sf = ts.tv_nsec;
#else
    sf = tv.tv_usec * 1000;
#endif

    if (of < -DAY_IN_SECONDS || of > DAY_IN_SECONDS) {
        of = 0;
        rb_warning("invalid offset is ignored");
    }

    decode_year(INT2FIX(y), -1, &nth, &ry);

    ret = d_complex_new_internal(klass,
                                 nth, 0,
                                 0, LONG2NUM(sf),
                                 (int)of, GREGORIAN,
                                 ry, m, d,
                                 h, min, s,
                                 HAVE_CIVIL | HAVE_TIME);
    {
        get_d1(ret);
        set_sg(dat, sg);
    }
    return ret;
}

ordinal([year=-4712[, yday=1[, hour=0[, minute=0[, second=0[, offset=0, start=Date::ITALY]]]]]]) → datetime Show source

创建一个表示给定的序号日期的DateTime对象。

代码语言:javascript
复制
DateTime.ordinal(2001,34) #=> #<DateTime: 2001-02-03T00:00:00+00:00 ...>
DateTime.ordinal(2001,34,4,5,6,'+7')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.ordinal(2001,-332,-20,-55,-54,'+7')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_ordinal(int argc, VALUE *argv, VALUE klass)
{
    VALUE vy, vd, vh, vmin, vs, vof, vsg, y, fr, fr2, ret;
    int d, h, min, s, rof;
    double sg;

    rb_scan_args(argc, argv, "07", &vy, &vd, &vh, &vmin, &vs, &vof, &vsg);

    y = INT2FIX(-4712);
    d = 1;

    h = min = s = 0;
    fr2 = INT2FIX(0);
    rof = 0;
    sg = DEFAULT_SG;

    switch (argc) {
      case 7:
        val2sg(vsg, sg);
      case 6:
        val2off(vof, rof);
      case 5:
        num2int_with_frac(s, positive_inf);
      case 4:
        num2int_with_frac(min, 4);
      case 3:
        num2int_with_frac(h, 3);
      case 2:
        num2int_with_frac(d, 2);
      case 1:
        y = vy;
    }

    {
        VALUE nth;
        int ry, rd, rh, rmin, rs, rjd, rjd2, ns;

        if (!valid_ordinal_p(y, d, sg,
                             &nth, &ry,
                             &rd, &rjd,
                             &ns))
            rb_raise(rb_eArgError, "invalid date");
        if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs))
            rb_raise(rb_eArgError, "invalid date");
        canon24oc();

        rjd2 = jd_local_to_utc(rjd,
                               time_to_df(rh, rmin, rs),
                               rof);

        ret = d_complex_new_internal(klass,
                                     nth, rjd2,
                                     0, INT2FIX(0),
                                     rof, sg,
                                     0, 0, 0,
                                     rh, rmin, rs,
                                     HAVE_JD | HAVE_TIME);
    }
    add_frac();
    return ret;
}

parse(string='-4712-01-01T00:00:00+00:00'[, comp=true, start=Date::ITALY]) → datetime Show source

解析给定的日期和时间表示,并创建一个DateTime对象。此方法不起验证器的作用。

如果可选的第二个参数为true并且检测到的年份在“00”至“99”范围内,则将其填满。

代码语言:javascript
复制
DateTime.parse('2001-02-03T04:05:06+07:00')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.parse('20010203T040506+0700')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.parse('3rd Feb 2001 04:05:06 PM')
                          #=> #<DateTime: 2001-02-03T16:05:06+00:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_parse(int argc, VALUE *argv, VALUE klass)
{
    VALUE str, comp, sg;

    rb_scan_args(argc, argv, "03", &str, &comp, &sg);

    switch (argc) {
      case 0:
        str = rb_str_new2("-4712-01-01T00:00:00+00:00");
      case 1:
        comp = Qtrue;
      case 2:
        sg = INT2FIX(DEFAULT_SG);
    }

    {
        VALUE argv2[2], hash;

        argv2[0] = str;
        argv2[1] = comp;
        hash = date_s__parse(2, argv2, klass);
        return dt_new_by_frags(klass, hash, sg);
    }
}

rfc2822(string='Mon, 1 Jan -4712 00:00:00 +0000', start=Date::ITALY) → datetime Show source

根据某些典型的RFC 2822格式通过解析字符串来创建新的DateTime对象。

代码语言:javascript
复制
DateTime.rfc2822('Sat, 3 Feb 2001 04:05:06 +0700')
                         #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_rfc2822(int argc, VALUE *argv, VALUE klass)
{
    VALUE str, sg;

    rb_scan_args(argc, argv, "02", &str, &sg);

    switch (argc) {
      case 0:
        str = rb_str_new2("Mon, 1 Jan -4712 00:00:00 +0000");
      case 1:
        sg = INT2FIX(DEFAULT_SG);
    }

    {
        VALUE hash = date_s__rfc2822(klass, str);
        return dt_new_by_frags(klass, hash, sg);
    }
}

rfc3339(string='-4712-01-01T00:00:00+00:00', start=Date::ITALY) → datetime Show source

根据某些典型的RFC 3339格式通过解析字符串来创建新的DateTime对象。

代码语言:javascript
复制
DateTime.rfc3339('2001-02-03T04:05:06+07:00')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_rfc3339(int argc, VALUE *argv, VALUE klass)
{
    VALUE str, sg;

    rb_scan_args(argc, argv, "02", &str, &sg);

    switch (argc) {
      case 0:
        str = rb_str_new2("-4712-01-01T00:00:00+00:00");
      case 1:
        sg = INT2FIX(DEFAULT_SG);
    }

    {
        VALUE hash = date_s__rfc3339(klass, str);
        return dt_new_by_frags(klass, hash, sg);
    }
}

rfc822(string='Mon, 1 Jan -4712 00:00:00 +0000', start=Date::ITALY) → datetime Show source

根据某些典型的RFC 2822格式通过解析字符串来创建新的DateTime对象。

代码语言:javascript
复制
DateTime.rfc2822('Sat, 3 Feb 2001 04:05:06 +0700')
                         #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_rfc2822(int argc, VALUE *argv, VALUE klass)
{
    VALUE str, sg;

    rb_scan_args(argc, argv, "02", &str, &sg);

    switch (argc) {
      case 0:
        str = rb_str_new2("Mon, 1 Jan -4712 00:00:00 +0000");
      case 1:
        sg = INT2FIX(DEFAULT_SG);
    }

    {
        VALUE hash = date_s__rfc2822(klass, str);
        return dt_new_by_frags(klass, hash, sg);
    }
}

strptime([string='-4712-01-01T00:00:00+00:00'[, format='%FT%T%z' ,start=Date::ITALY]]) → datetime Show source

用给定的模板解析给定的日期和时间表示,并创建一个DateTime对象。strptime不支持与strftime不同的标志和宽度的规范。

代码语言:javascript
复制
DateTime.strptime('2001-02-03T04:05:06+07:00', '%Y-%m-%dT%H:%M:%S%z')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.strptime('03-02-2001 04:05:06 PM', '%d-%m-%Y %I:%M:%S %p')
                          #=> #<DateTime: 2001-02-03T16:05:06+00:00 ...>
DateTime.strptime('2001-W05-6T04:05:06+07:00', '%G-W%V-%uT%H:%M:%S%z')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.strptime('2001 04 6 04 05 06 +7', '%Y %U %w %H %M %S %z')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.strptime('2001 05 6 04 05 06 +7', '%Y %W %u %H %M %S %z')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
DateTime.strptime('-1', '%s')
                          #=> #<DateTime: 1969-12-31T23:59:59+00:00 ...>
DateTime.strptime('-1000', '%Q')
                          #=> #<DateTime: 1969-12-31T23:59:59+00:00 ...>
DateTime.strptime('sat3feb014pm+7', '%a%d%b%y%H%p%z')
                          #=> #<DateTime: 2001-02-03T16:00:00+07:00 ...>

另见strptime(3)和strftime。

代码语言:javascript
复制
static VALUE
datetime_s_strptime(int argc, VALUE *argv, VALUE klass)
{
    VALUE str, fmt, sg;

    rb_scan_args(argc, argv, "03", &str, &fmt, &sg);

    switch (argc) {
      case 0:
        str = rb_str_new2("-4712-01-01T00:00:00+00:00");
      case 1:
        fmt = rb_str_new2("%FT%T%z");
      case 2:
        sg = INT2FIX(DEFAULT_SG);
    }

    {
        VALUE argv2[2], hash;

        argv2[0] = str;
        argv2[1] = fmt;
        hash = date_s__strptime(2, argv2, klass);
        return dt_new_by_frags(klass, hash, sg);
    }
}

xmlschema(string='-4712-01-01T00:00:00+00:00', start=Date::ITALY) → datetime Show source

根据一些典型的XML Schema格式,通过解析字符串来创建新的DateTime对象。

代码语言:javascript
复制
DateTime.xmlschema('2001-02-03T04:05:06+07:00')
                          #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
代码语言:javascript
复制
static VALUE
datetime_s_xmlschema(int argc, VALUE *argv, VALUE klass)
{
    VALUE str, sg;

    rb_scan_args(argc, argv, "02", &str, &sg);

    switch (argc) {
      case 0:
        str = rb_str_new2("-4712-01-01T00:00:00+00:00");
      case 1:
        sg = INT2FIX(DEFAULT_SG);
    }

    {
        VALUE hash = date_s__xmlschema(klass, str);
        return dt_new_by_frags(klass, hash, sg);
    }
}

公共实例方法

as_json(*) Show source

返回一个散列,它将变成一个JSON对象并表示这个对象。

代码语言:javascript
复制
# File ext/json/lib/json/add/date_time.rb, line 28
def as_json(*)
  {
    JSON.create_id => self.class.name,
    'y' => year,
    'm' => month,
    'd' => day,
    'H' => hour,
    'M' => min,
    'S' => sec,
    'of' => offset.to_s,
    'sg' => start,
  }
end

iso8601(n=0) → string Show source

xmlschema(n=0) → string

此方法等效于strftime('%FT%T')。可选参数n是小数秒的位数。

代码语言:javascript
复制
DateTime.parse('2001-02-03T04:05:06.123456789+07:00').iso8601(9)
                          #=> "2001-02-03T04:05:06.123456789+07:00"
代码语言:javascript
复制
static VALUE
dt_lite_iso8601(int argc, VALUE *argv, VALUE self)
{
    long n = 0;

    rb_check_arity(argc, 0, 1);
    if (argc >= 1)
        n = NUM2LONG(argv[0]);

    return rb_str_append(strftimev("%Y-%m-%d", self, set_tmx),
                         iso8601_timediv(self, n));
}

jisx0301(n=0) → string Show source

返回JIS X 0301格式的字符串。可选参数n是小数秒的长度。

代码语言:javascript
复制
DateTime.parse('2001-02-03T04:05:06.123456789+07:00').jisx0301(9)
                          #=> "H13.02.03T04:05:06.123456789+07:00"
代码语言:javascript
复制
static VALUE
dt_lite_jisx0301(int argc, VALUE *argv, VALUE self)
{
    long n = 0;

    rb_check_arity(argc, 0, 1);
    if (argc >= 1)
        n = NUM2LONG(argv[0]);

    return rb_str_append(d_lite_jisx0301(self),
                         iso8601_timediv(self, n));
}

rfc3339(n=0) → string Show source

此方法等效于strftime('%FT%T')。可选参数n是小数秒的长度。

代码语言:javascript
复制
DateTime.parse('2001-02-03T04:05:06.123456789+07:00').rfc3339(9)
                          #=> "2001-02-03T04:05:06.123456789+07:00"
代码语言:javascript
复制
static VALUE
dt_lite_rfc3339(int argc, VALUE *argv, VALUE self)
{
    return dt_lite_iso8601(argc, argv, self);
}

strftime(format='%FT%T%:z') → string Show source

根据给定格式字符串中的指令格式化日期。指令以百分号(%)字符开头。任何未作为指令列出的文本都将传递到输出字符串。

该指令由一个百分号(%)字符,零个或多个标志,可选的最小字段宽度,可选的修饰符和转换说明符组成,如下所示。

代码语言:javascript
复制
%<flags><width><modifier><conversion>

Flags:

代码语言:javascript
复制
-  don't pad a numerical output.
_  use spaces for padding.
0  use zeros for padding.
^  upcase the result string.
#  change case.
:  use colons for %z.

最小字段宽度指定最小宽度。

修饰符是“E”和“O”。他们被忽略。

格式指南:

代码语言:javascript
复制
Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)   %15N femtosecond (15 digits)
          %6N  microsecond (6 digits)   %18N attosecond  (18 digits)
          %9N  nanosecond  (9 digits)   %21N zeptosecond (21 digits)
          %12N picosecond (12 digits)   %24N yoctosecond (24 digits)

Time zone:
  %z - Time zone as hour and minute offset from UTC (e.g. +0900)
          %:z - hour and minute offset from UTC with a colon (e.g. +09:00)
          %::z - hour, minute and second offset from UTC (e.g. +09:00:00)
          %:::z - hour, minute and second offset from UTC
                                            (e.g. +09, +09:30, +09:30:30)
  %Z - Time zone abbreviation name or something similar information.

Weekday:
  %A - The full weekday name (``Sunday'')
          %^A  uppercased (``SUNDAY'')
  %a - The abbreviated name (``Sun'')
          %^a  uppercased (``SUN'')
  %u - Day of the week (Monday is 1, 1..7)
  %w - Day of the week (Sunday is 0, 0..6)

ISO 8601 week-based year and week number:
The week 1 of YYYY starts with a Monday and includes YYYY-01-04.
The days in the year before the first week are in the last week of
the previous year.
  %G - The week-based year
  %g - The last 2 digits of the week-based year (00..99)
  %V - Week number of the week-based year (01..53)

Week number:
The week 1 of YYYY starts with a Sunday or Monday (according to %U
or %W).  The days in the year before the first week are in week 0.
  %U - Week number of the year.  The week starts with Sunday.  (00..53)
  %W - Week number of the year.  The week starts with Monday.  (00..53)

Seconds since the Unix Epoch:
  %s - Number of seconds since 1970-01-01 00:00:00 UTC.
  %Q - Number of milliseconds since 1970-01-01 00:00:00 UTC.

Literal string:
  %n - Newline character (\n)
  %t - Tab character (\t)
  %% - Literal ``%'' character

Combination:
  %c - date and time (%a %b %e %T %Y)
  %D - Date (%m/%d/%y)
  %F - The ISO 8601 date format (%Y-%m-%d)
  %v - VMS date (%e-%b-%Y)
  %x - Same as %D
  %X - Same as %T
  %r - 12-hour time (%I:%M:%S %p)
  %R - 24-hour time (%H:%M)
  %T - 24-hour time (%H:%M:%S)
  %+ - date(1) (%a %b %e %H:%M:%S %Z %Y)

该方法与ISO C和POSIX中定义的strftime()函数类似。几个指令(%a,%A,%b,%B,%c,%p,%r,%x,%X,%E *,%O *和%Z)在语言环境中依赖于函数。但是,这种方法是独立于区域的。因此,即使在其他系统(如C)中使用相同的格式字符串,结果也可能不同。因为存在相应的与区域无关的表示形式%D和%T,所以避免使用%x和%X是一种好的做法。

例子:

代码语言:javascript
复制
d = DateTime.new(2007,11,19,8,37,48,"-06:00")
                          #=> #<DateTime: 2007-11-19T08:37:48-0600 ...>
d.strftime("Printed on %m/%d/%Y")   #=> "Printed on 11/19/2007"
d.strftime("at %I:%M%p")            #=> "at 08:37AM"

各种ISO 8601格式:

代码语言:javascript
复制
%Y%m%d           => 20071119                  Calendar date (basic)
%F               => 2007-11-19                Calendar date (extended)
%Y-%m            => 2007-11                   Calendar date, reduced accuracy, specific month
%Y               => 2007                      Calendar date, reduced accuracy, specific year
%C               => 20                        Calendar date, reduced accuracy, specific century
%Y%j             => 2007323                   Ordinal date (basic)
%Y-%j            => 2007-323                  Ordinal date (extended)
%GW%V%u          => 2007W471                  Week date (basic)
%G-W%V-%u        => 2007-W47-1                Week date (extended)
%GW%V            => 2007W47                   Week date, reduced accuracy, specific week (basic)
%G-W%V           => 2007-W47                  Week date, reduced accuracy, specific week (extended)
%H%M%S           => 083748                    Local time (basic)
%T               => 08:37:48                  Local time (extended)
%H%M             => 0837                      Local time, reduced accuracy, specific minute (basic)
%H:%M            => 08:37                     Local time, reduced accuracy, specific minute (extended)
%H               => 08                        Local time, reduced accuracy, specific hour
%H%M%S,%L        => 083748,000                Local time with decimal fraction, comma as decimal sign (basic)
%T,%L            => 08:37:48,000              Local time with decimal fraction, comma as decimal sign (extended)
%H%M%S.%L        => 083748.000                Local time with decimal fraction, full stop as decimal sign (basic)
%T.%L            => 08:37:48.000              Local time with decimal fraction, full stop as decimal sign (extended)
%H%M%S%z         => 083748-0600               Local time and the difference from UTC (basic)
%T%:z            => 08:37:48-06:00            Local time and the difference from UTC (extended)
%Y%m%dT%H%M%S%z  => 20071119T083748-0600      Date and time of day for calendar date (basic)
%FT%T%:z         => 2007-11-19T08:37:48-06:00 Date and time of day for calendar date (extended)
%Y%jT%H%M%S%z    => 2007323T083748-0600       Date and time of day for ordinal date (basic)
%Y-%jT%T%:z      => 2007-323T08:37:48-06:00   Date and time of day for ordinal date (extended)
%GW%V%uT%H%M%S%z => 2007W471T083748-0600      Date and time of day for week date (basic)
%G-W%V-%uT%T%:z  => 2007-W47-1T08:37:48-06:00 Date and time of day for week date (extended)
%Y%m%dT%H%M      => 20071119T0837             Calendar date and local time (basic)
%FT%R            => 2007-11-19T08:37          Calendar date and local time (extended)
%Y%jT%H%MZ       => 2007323T0837Z             Ordinal date and UTC of day (basic)
%Y-%jT%RZ        => 2007-323T08:37Z           Ordinal date and UTC of day (extended)
%GW%V%uT%H%M%z   => 2007W471T0837-0600        Week date and local time and difference from UTC (basic)
%G-W%V-%uT%R%:z  => 2007-W47-1T08:37-06:00    Week date and local time and difference from UTC (extended)

另请参阅strftime(3)和:: strptime。

代码语言:javascript
复制
static VALUE
dt_lite_strftime(int argc, VALUE *argv, VALUE self)
{
    return date_strftime_internal(argc, argv, self,
                                  "%Y-%m-%dT%H:%M:%S%:z", set_tmx);
}

to_date → date Show source

返回一个表示self的Date对象。

代码语言:javascript
复制
static VALUE
datetime_to_date(VALUE self)
{
    get_d1a(self);

    if (simple_dat_p(adat)) {
        VALUE new = d_lite_s_alloc_simple(cDate);
        {
            get_d1b(new);
            bdat->s = adat->s;
            bdat->s.jd = m_local_jd(adat);
            return new;
        }
    }
    else {
        VALUE new = d_lite_s_alloc_simple(cDate);
        {
            get_d1b(new);
            copy_complex_to_simple(new, &bdat->s, &adat->c)
            bdat->s.jd = m_local_jd(adat);
            bdat->s.flags &= ~(HAVE_DF | HAVE_TIME | COMPLEX_DAT);
            return new;
        }
    }
}

to_datetime → self Show source

返回自我。

代码语言:javascript
复制
static VALUE
datetime_to_datetime(VALUE self)
{
    return self;
}

to_json(*args) Show source

将Julian year y,month m,day d,hour H,minute M,second S,offset of和日历改革日期的类名称(DateTime)存储sg为JSON字符串

代码语言:javascript
复制
# File ext/json/lib/json/add/date_time.rb, line 45
def to_json(*args)
  as_json.to_json(*args)
end

to_s → string Show source

返回ISO 8601格式的字符串。(此方法不使用扩展表示。)

代码语言:javascript
复制
DateTime.new(2001,2,3,4,5,6,'-7').to_s
                         #=> "2001-02-03T04:05:06-07:00"
代码语言:javascript
复制
static VALUE
dt_lite_to_s(VALUE self)
{
    return strftimev("%Y-%m-%dT%H:%M:%S%:z", self, set_tmx);
}

to_time → time Show source

返回表示自我的Time对象。

代码语言:javascript
复制
static VALUE
datetime_to_time(VALUE self)
{
    volatile VALUE dup = dup_obj(self);
    {
        VALUE t;

        get_d1(dup);

        t = rb_funcall(rb_cTime,
                   rb_intern("new"),
                   7,
                   m_real_year(dat),
                   INT2FIX(m_mon(dat)),
                   INT2FIX(m_mday(dat)),
                   INT2FIX(m_hour(dat)),
                   INT2FIX(m_min(dat)),
                   f_add(INT2FIX(m_sec(dat)),
                         m_sf_in_sec(dat)),
                   INT2FIX(m_of(dat)));
        return t;
    }
}

iso8601(n=0) → string Show source

xmlschema(n=0) → string

此方法等效于strftime('%FT%T')。可选参数n是小数秒的位数。

代码语言:javascript
复制
DateTime.parse('2001-02-03T04:05:06.123456789+07:00').iso8601(9)
                          #=> "2001-02-03T04:05:06.123456789+07:00"
代码语言:javascript
复制
static VALUE
dt_lite_iso8601(int argc, VALUE *argv, VALUE self)
{
    long n = 0;

    rb_check_arity(argc, 0, 1);
    if (argc >= 1)
        n = NUM2LONG(argv[0]);

    return rb_str_append(strftimev("%Y-%m-%d", self, set_tmx),
                         iso8601_timediv(self, n));
}

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com