Ruby - DateTime for Database - ruby

I have a Database column with the syntax "0000-00-00 00:00:00".
In PHP I would do
date('Y-m-d H:i:s');
In Ruby, I do
require 'date'
now = DateTime::now()
puts "#{now.year()}-#{now.mon()}-#{now.mday()} #{now.hour()}:#{now.min()}:#{now.sec()}"
The result is:
"2010-1-5 10:16:4"
That's not okay. How could I create a "timestring" with the format "0000-00-00 00:00:00"?
Thanks a lot in advance & Best Regards

You can format the dates like in PHP thanks to the built-in Time class, see documentation there.
This would give for your case :
t = Time.now
puts t.strftime("%Y-%m-%d %H:%M:%S")

A little shorter
t = Time.now
puts t.strftime("%F %T")
=> "2015-01-06 14:01:05"

iso8601 method can be useful also:
>> Time.now.utc.iso8601
=> "2015-05-08T16:45:22Z"

If you're using Rails/ActiveSupport then to_s(:db) will be the shortest way:
Time.now.to_s(:db)
=> "2017-05-22 11:14:40"

ActiveRecord tends to store dates / times as UTC, so using utc will make your data more consistant
t = Time.now.utc
puts t.strftime("%F %T")
=> "2016-05-06 19:05:01"

Note that Rails also stores microsecond precision. That is, microseconds are the 6 digits after the second in the database format:
Time.now.strftime('%Y-%m-%d %H:%M:%S.%6N')
=> "2022-10-26 12:30:26.243506"
or:
Time.now.strftime('%F %T.%6N')
=> "2022-10-26 12:34:37.803091"

Related

why is the hours missing on time transformation?

The time stamp is missing on the parsing. What needs to be done to ensure that the timestamp is also there?
irb(main):060:0> dt= Date.parse "2021-08-06T15:00:00-04:00"
=> #<Date: 2021-08-06 ((2459433j,0s,0n),+0s,2299161j)>
irb(main):061:0> dt.strftime("%Y-%m-%d %H:%M:%S.%L")
=> "2021-08-06 00:00:00.000"
Consider using DateTime:
require 'date'
dt = DateTime.parse("2021-08-06T15:00:00+04:00")
result = dt.strftime("%Y-%m-%d %H:%M:%S.%L")
puts result
Yielding 2021-08-06 15:00:00.000.

Get start and end epoch times for today

I'm using an API that requires a start_time and an end_time in epoch that will give me data between those times. The question is I want all the data from the start of UTC today to the end of UTC today.
What's the most effective way to do this in ruby?
You can use the ActiveSupport Date functions #beginning_of_day and #end_of_day. And use to_i to convert the time to seconds since Epoch.
require 'active_support/core_ext'
Date.today.beginning_of_day.to_i
# => 1395532800
Date.today.end_of_day.to_i
# => 1395619199
Date.today.to_time.to_i
should get you the start, and
(Date.today + 1).to_time.to_i
should get you the end.
If you are not using rails or do not wish to import require 'active_support/core_ext' for some reason you can do it using ruby as follows
Date.today.to_time.to_i # beginning_of_day
=> 1481221800
Date.today.to_time.change(hour: 23, min: 59, sec: 59).to_i # end_of_day
=> 1481308199

How to get the current month with Sequel

I would like recover a list of entries for the current month with Sequel.
I tried:
Entry.where(:date >= Date.month).sum(:duration)
or
Entry.where(:date.like('%/06/2013')).sum(:duration)
and other ways, but none of them seemed to work.
If you want all entries the current month and the current year, it's probably easiest to use a range:
d = Date.today
Entry.where(:date=> Date.new(d.year, d.month)...(Date.new(d.year, d.month) >> 1)).sum(:duration)
If you want the current month in any year, Sequel has built in support for this:
Entry.where(Sequel.extract(:month, :date) => Date.today.month).sum(:duration)
You'll need to think in terms of how a database thinks, and how Sequel turns Ruby ranges into SQL:
require 'date'
today = Date.today # => #<Date: 2013-07-03 ((2456477j,0s,0n),+0s,2299161j)>
first_of_month = (today - today.day) + 1
first_of_month # => #<Date: 2013-07-01 ((2456475j,0s,0n),+0s,2299161j)>
next_month = today + 31 # => #<Date: 2013-08-03 ((2456508j,0s,0n),+0s,2299161j)>
last_of_month = next_month - next_month.day # => #<Date: 2013-07-31 ((2456505j,0s,0n),+0s,2299161j)>
last_of_month # => #<Date: 2013-07-31 ((2456505j,0s,0n),+0s,2299161j)>
Entry.where(:date => [first_of_month .. last_of_month]).sum(:duration)
I'd show you the SQL output, but I don't know the database type you're using, and, well, I'm lazy.
Often, you can play tricks inside the DB by truncating "now" to remove the day, then finding all timestamps whose truncated date matches it. That's a lot more specific to the DBM than using Sequel, which already knows how to deal with ranges when converting them to a "between"-type statement.

looking for a method that will show tomorrow's date in ruby

Though, I already got the answer to my question, I decided to edit it.
I was looking for any method in Ruby that can show tomorrow's date.
It's ok if it will show the time as well, I will format its output.
The Time.now gives current date, time and timezone:
Time.now
=> 2013-06-11 13:09:02 +0900
How can I use this method to get a date for tomorrow?
It's ok if there are other methods that can do it.
require 'date'
tomorrow = Date.today + 1
tomorrow is a date object. You can print it in the format you want.
Try:
Time.now + 24*60*60
(Edited: xaxxon is right. My earlier version used Rails' functionality)
ruby 2.6+ helper method
Date.tomorrow
Similar to Stu Gla:
today = Time.now
tomorrow = today + (60 * 60 * 24)
you can then use the .strftime method to format... example:
puts tomorrow.strftime("%F")
# => 2014-08-07

Ruby DateTime.Parse to local time

I have a date string 20101129220021, so I will use
require 'date'
d = DateTime.parse('20101129220021')
This part works fine, and I get a date, which is in UTC.
My question is, how can I convert this into my local time? I tried many methods like extracting the time part using d.to_time and manipulate the result, but it didn't work. As far as I know, DateTime object is immutable. Can I please get some help?
irb(main):001:0> require "date"
=> true
irb(main):002:0> d = DateTime.parse('20101129220021')
=> #<DateTime: 2010-11-29T22:00:21+00:00 (70719276007/28800,0/1,2299161)>
irb(main):003:0> d.to_time
=> 2010-11-30 00:00:21 +0200
ruby 1.9.2p180 (2011-02-18)
You can add a rational fraction based on the timezone to get the local time.
require 'date'
# Make this whatever your zone is. Using UTC +0300 here.
ZONE = 3
d = DateTime.parse('20101129220021') + Rational(ZONE,24)
d.to_s # => "2010-11-30T01:00:21+00:00"

Resources