@Konboi memo

主に技術に関してつらつらと。

Rubyで文字列からTime型または DateTime型に変換する

API等で

{
  “start_at”: “2013-11-22 17:30:00 +0900”,
  “end_at”: “2013-11-25 17:30:00 +0900”
}

こんな感じで時間が文字列で送られてきた時に Time型、または DateTime型 start_at と end_at で計算をしたいときには

parse メソッドを使って変換ができます。

※ただし、time型に変換する場合は require ‘time’する必要があります。

require 'time'

start_time = "2013-11-22 17:30:00 +0900"
end_time   = "2013-11-25 17:30:00 +0900"

start_time_to_time = Time.parse(start_time)
end_time_to_time   = Time.parse(end_time)

start_time_to_date_time = DateTime.parse(start_time)
end_time_to_date_time   = DateTime.parse(end_time)

"----start_time, end_time---------"
puts start_time.class
puts end_time.class

"----start_time_to_time, end_time_to_time---------"

puts start_time_to_time.class
puts end_time_to_time.class

"----start_time_to_date_time, end_time_to_date_time---------"

puts start_time_to_date_time.class
puts end_time_to_date_time.class
----start_time, end_time---------
String
String
----start_time_to_time, end_time_to_time---------
Time
Time
----start_time_to_date_time, end_time_to_date_time---------
DateTime
DateTime

このようになります。

最後に

Time型とDatetime型なら??

同じように扱えるならTime型とDateTime型どっち使うのがおすすめなの?

ってとなると思いますが。

puts "------ Time ------"
puts start_time_to_time
puts start_time_to_time + 1


puts "------ DateTime ------"
puts start_time_to_date_time
puts start_time_to_date_time + 1
------ Time ------
2013-11-22 17:30:00 +0900
2013-11-22 17:30:01 +0900
------ DateTime ------
2013-11-22T17:30:00+09:00
2013-11-23T17:30:00+09:00

この例のように Time型は +1 すると 1秒プラスされ、 DateTime型は 1日 プラスされるという違いはあるものの。 それ以外は使う上であまり差は無いかなという印象なので、好きな方を使えばいいと思います。

たのしいRuby 第4版
たのしいRuby 第4版
posted with amazlet at 13.11.26
高橋 征義 後藤 裕蔵
ソフトバンククリエイティブ
売り上げランキング: 52,850