MC, 11:35 wtorek, 21.04.2015 r.
Ilustracja do artykułu: Ruby - Mutual conversion between Date and UNIX timestamp

Ruby - Mutual conversion between Date and UNIX timestamp

This time it will be a short note presenting a way to mutual conversion between Date object to UNIX timestamp in Ruby language.

How to convert Date to UNIX timestamp?

The conversion from Date object to UNIX timestamp is divided into two stages: firstly we convert Date object to Time one using to_time method and then we count UNIX time by method to_i. Please look at the output from console:
require 'date'
=> true
Date.new(2015,4,21).to_time
=> 2015-04-21 00:00:00 +0000
Date.new(2015,4,21).to_time.to_i
=> 1429574400

How to convert UNIX timestamp to Date?

If we are interested in conversion in opposite direction we need to make Time object from UNIX timestamp by using at method and after that we can get Date object as a result of to_date method, like it is shown below:
require 'date'
=> true
Time.at(1429574400)
=> 2015-04-21 00:00:00 +0000
Time.at(1429574400).to_date
=> #<Date: 2015-04-21 ((2457134j,0s,0n),+0s,2299161j)>

Komentarze (0) - Nikt jeszcze nie komentował - bądź pierwszy!

Imię:
Treść:
Polish version: Ruby - Konwersja między Date a UNIX timestamp