Skip to content

Instantly share code, notes, and snippets.

@ohnishiakira
Created February 1, 2012 05:09
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohnishiakira/1715230 to your computer and use it in GitHub Desktop.
Save ohnishiakira/1715230 to your computer and use it in GitHub Desktop.
DateTimeの差を秒単位で取る
# 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