Rails Convert UNIX timestamp to SQL DateTime - ruby-on-rails

I have timestamp as "1432927800000"
I want to save it in DateTime column of MySQL. (SQL DateTime column stores date in this format : 2010-06-24 11:30:00)
I have tried
uTime = params[:fromDate] #contains "1432927800000"
Date.new(uTime).to_formatted_s(:db) #Comparison of String with 0 failed.
DateTime.strptime("1318996912",'%s') #Give weird date: Wed, 03 Sep 47377 12:00:00 +0000
Date.parse(uTime).to_s(:db) #Invalid Date
I am expecting 2015-5-30 1:00:00 from "1432927800000"

Instead of strftime will be better to use predefined :db pattern from ActiveSupport:
2.1.0 :002 > Time.at(1432927800000/1000).to_s(:db)
=> "2015-05-29 22:30:00"
to_s is alias for to_formatted_s method and defined in Time and DateTime classes.

Try this I Hope this will help you
I have tried it in my Rails console and I got following.
uTime = 1432927800000
Time.at(uTime/1000).strftime("%Y-%m-%d %I:%M:%S")
## Output
"2015-05-30 01:00:00"
This a link where you which will helps you to convert unix timestamp
http://www.epochconverter.com/

Related

Subtracting dates in ruby or rails

I have the following:
due_date = Date.parse '2020-07-18 00:00:00 -0700'
today_date = Time.now
(due_date - today_date).to_i
I start out by converting the date string (this is a string, not an ActiveRecord datetime object), into a date object.
Then I create a new date object using Time.now, but when I try to subtract, I get an error:
(note that I am running this inside a Rails console):
irb(main):001:0> due_date = Date.parse '2020-07-18 00:00:00 -0700'
=> Sat, 18 Jul 2020
irb(main):002:0> today_date = Time.now
=> 2020-04-22 17:39:17 -0700
irb(main):003:0> (due_date - today_date).to_i
Traceback (most recent call last):
1: from (irb):3
TypeError (expected numeric)
I thought I can subtract the two date object to come up with difference in days. Any ideas?
Date and Time are not the same class so you can't just subtract one from the other.
Try using DateTime instead or coercing time into a date using to_date.
due_date = DateTime.parse '2020-07-18 00:00:00 -0700'
today_date = DateTime.current
(due_date - today_date).to_i
Also be careful using Time.now because it's not time zone aware (https://thoughtbot.com/blog/its-about-time-zones)

Can't get the right DateTime (Ruby on Rails)

I have a column that has a datetime data types.
Whenever I update the column like this.
new_date = "2014-12-13 03:43:30".to_datetime
Model.first.update_column(:my_datetime, new_date) => true
But when I do quest like this.
Model.first.my_datetime => "Sat, 13 Dec 2014 11:43:30 HKT +08:00"
It supposed to output 03:43:30
Please help thanks!
you are looking for strftime:
new_date.strftime("%T")
#=> "03:43:30"
or applying it on activerecord response:
new_date = "2014-12-13 03:43:30".to_datetime
Model.first.update_column(:my_datetime, new_date)
#=> true
Model.first.my_datetime.strftime("%T")
#=> "03:43:30"
Here %T is for Local time (extended)
You need to change the Zone
Use Time.zone.now

Rails convert string containing datetime to date

I have a String which contains the following string 2012-03-06 00:00:00 UTC I want to change it into a date object so that is should look like this 03-06-2012 and the same is to be converted in String 03-06-2012 so that the jquery datepicker can take it.
All this conversion needs to be done at view .html.erb
Date.parse("2012-03-06 00:00:00 UTC").strftime("%d-%m-%Y")
You can do this
date = DateTime.now
puts date.to_date.to_s
which gives "2013-08-21"
date = Date.parse('2012-03-06 00:00:00 UTC')
# => Tue, 06 Mar 2012
date.strftime('%d-%m-%Y')
# => "06-03-2012"

Comparing dates in rails

Suppose I have a standard Post.first.created_at datetime. Can I compare that directly with a datetime in the format 2009-06-03 16:57:45.608000 -04:00 by doing something like:
Post.first.created_at > Time.parse("2009-06-03 16:57:45.608000 -04:00")
Edit: Both fields are datetimes, not dates.
Yes, you can use comparison operators to compare dates e.g.:
irb(main):018:0> yesterday = Date.new(2009,6,13)
=> #<Date: 4909991/2,0,2299161>
irb(main):019:0> Date.today > yesterday
=> true
But are you trying to compare a date to a datetime?
If that's the case, you'll want to convert the datetime to a date then do the comparison.
I hope this helps.
Yes you can compare directly the value of a created_at ActiveRecord date/time field with a regular DateTime object (like the one you can obtain parsing the string you have).
In a project i have a Value object that has a created_at datetime object:
imac:trunk luca$ script/console
Loading development environment (Rails 2.3.2)
>> Value.first.created_at
=> Fri, 12 Jun 2009 08:00:45 CEST 02:00
>> Time.parse("2009-06-03 16:57:45.608000 -04:00")
=> Wed Jun 03 22:57:45 0200 2009
>> Value.first.created_at > Time.parse("2009-06-03 16:57:45.608000 -04:00")
=> true
The created_at field is defined as:
create_table "values", :force => true do |t|
[...]
t.datetime "created_at"
end
N.B. if your field is a date and not a datetime, then you need to convert it to a time:
Post.first.created_at.to_time > Time.parse("2009-06-03 16:57:45.608000 -04:00")
or parse a date:
Post.first.created_at > Date.parse("2009-06-03 16:57:45.608000 -04:00")
otherwise you'll get a:
ArgumentError: comparison of Date with Time failed

Ruby on Rails - how to display a date in format i need? Converting from YYYY-MM-DD HH:MM:SS UTC to MM/DD/YYYY

I am a RoR newbie. I tried a lot of things, finally came to following:
<td>
<%= Date.strptime(request.baseline_start_date, "%Y-%M-%D %H:%M:%S %Z").strftime("%M/%D/%Y")%>
</td>
But this is also giving me an error:
$_ value need to be String (nil given)
But I know that request.baseline_start_date gives me value (tried printing it separately). I don't know which one it is saying as nil given.
Any suggestions on how I can achieve format conversion?
In Rails you can use the to_time function on a string to convert it into a Date object:
'2012-11-14 14:27:46'.to_time.strftime('%B %e at %l:%M %p')
#=> "November 14 at 2:27 PM"
For a handy, interactive reference guide, refer to http://www.foragoodstrftime.com/
Date.strptime(
"2009-04-24 18:33:41 UTC",
"%Y-%m-%d %H:%M:%S %Z"
).strftime("%m/%d/%Y")
# => "04/24/2009"
I think maybe you just got the capitalization on your format strings wrong.
Check the active support documentation and examples at:
http://apidock.com/rails/ActiveSupport/CoreExtensions/DateTime/Conversions/to_formatted_s
Examples
datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
datetime.to_s(:db) # => "2007-12-04 00:00:00"
datetime.to_s(:number) # => "20071204000000"
datetime.to_formatted_s(:short) # => "04 Dec 00:00"
datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
Or if you really want to customise it, define the helper like:
def custom_format(time)
Time::DATE_FORMATS[:w3cdtf] = lambda { |time| time.strftime("%Y-%m-%dT%H:%M:%S# {time.formatted_offset}") }
end
You can use the String#to_time (or Date#to_time) function in ActiveSupport to convert the string into a Time (or Date) object. Then use strftime as you have already.
Ive written a really nice gem that simplifies the whole process, and makes date formatting DRY.
Check it out at:
http://github.com/platform45/easy_dates
What I have done is add an initializer named conversions.rb in config/initializer
After that Add a line like follows:
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.update(:<name> => '<formatting>')
From there on you can render your datetime using your format with:
dateVar.to_s(:<name>)
There is a handy list here of the formatting tokens
Thanks a lot for the reply. My problem is, the output seems to be already string and i have to convert from date in string to another format.
When I look at the date stored in database (Oracle) it is mm/dd/yy, but when i get it displayed, it adds the timestamp and timezone.
I tried setting the default in Configuration\environment.rb as
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
:default => '%d %b %Y'
)
But that also doesn't seem to help.
At the end, if I just get the string to convert from Timezone format to mm/dd/yyyy, that is enough.

Resources