将1毫秒添加到Time / DateTime对象

时间:2016-09-28 11:51:53

标签: ruby time milliseconds

有没有办法在Ruby中为Time / DateTime对象添加1毫秒?

对于Web服务请求,我需要一个以毫秒为单位的时间范围:

irb(main):034:0> time_start = Date.today.to_time.utc.iso8601(3)
=> "2016-09-27T22:00:00.000Z"

irb(main):035:0> time_end = ((Date.today + 1).to_time).utc.iso8601(3)
=> "2016-09-28T22:00:00.000Z"
-- or --
irb(main):036:0> time_end = ((Date.today + 1).to_time - 1).utc.iso8601(3)
=> "2016-09-28T21:59:59.000Z"

所以我接近我的首选解决方案,但time_end应为2016-09-28T21:59:59.999Z

我没有找到Ruby可以用毫秒来处理计算的解决方案。我只用strftime做过,但如果有可能计算它会很棒。

-- This works, but hard coded --
time_end = ((Date.today + 1).to_time - 1).utc.strftime("%Y-%m-%dT%H:%M:%S.999Z")
=> "2016-09-28T21:59:59.999Z"

仅供参考:我是普通的Ruby,没有Rails。

1 个答案:

答案 0 :(得分:4)

好的,我找到了解决方案。通过实际计算我看起来像。

irb(main):055:0> Date.today.to_time.iso8601(3)
=> "2016-09-28T00:00:00.000+02:00

示例

iso8601(3)中的格式化仅用于显示行为。

irb(main):058:0> (Date.today.to_time + 1/1000.0).iso8601(3)
=> "2016-09-28T00:00:00.001+02:00"

添加毫秒"

!DONT USE, see result with subtracted 2 milliseconds!
irb(main):060:0> (Date.today.to_time - 1/1000.0).iso8601(3)
=> "2016-09-27T23:59:59.998+02:00"

USE
irb(main):061:0> (Date.today.to_time - 1/1001.0).iso8601(3)
=> "2016-09-27T23:59:59.999+02:00"

减去一毫秒

class Foo {
    public static function __callStatic($name, $args){
        if($name == "getBar"){
            return "Bar";
        }
        return NULL;
    }

    public function __call($name, $args){
        if($name == "getFoo"){
            $model = "Foo";
            $method = "getBar";            
            return $model::$method();            
        }
        return NULL;
    }
}

class Foo2 {
    public function __call($name, $args){
        if($name == "getFoo"){
            $model = "Foo";
            $method = "getBar";            
            return $model::$method();            
        }
        return NULL;
    }
}

echo Foo::getBar();//Bar

$foo = new Foo;
var_dump($foo->getFoo()); //Null though I'm expecting Bar

$foo = new Foo2;
var_dump($foo->getFoo()); //Bar