Created
February 1, 2012 05:09
-
-
Save ohnishiakira/1715230 to your computer and use it in GitHub Desktop.
DateTimeの差を秒単位で取る
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
require "date" | |
a = DateTime.new(2012, 1, 31, 23, 59, 55, "+09:00") | |
b = DateTime.new(2012, 2, 1, 0, 0, 0, "+09:00") | |
# (DateTime - DateTime)はRationalになるので、24 * 60 * 60をかけてto_iして秒単位に変換する | |
(b - a) # => (1/17500) | |
(b - a).class # => Rational | |
(b - a) * 24 * 60 * 60 # => (5/1) | |
((b - a) * 24 * 60 * 60).to_i # => 5 | |
# DateTimeをTimeに変換してto_iしたものを引く | |
b.to_time # => 2012-02-01 00:00:00 +0900 | |
a.to_time # => 2012-01-31 23:59:55 +0900 | |
b.to_time.class # => Time | |
a.to_time.class # => Time | |
b.to_time.to_i # => 1328054400 | |
a.to_time.to_i # => 1328054395 | |
(b.to_time.to_i - a.to_time.to_i) # => 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment