Ruby doesn't want to format string to date - ruby

I need to format a string to date:
date = DateTime.parse("05/15/2017")
formatted_date = date.strftime('%m/%d/%Y')
puts formatted_date
But I'm getting an error:
`parse': invalid date (ArgumentError)
And if I try to parse 15/05/2017 then it works.
How to parse 05/15/2017 into %m/%d/%Y format?

It is the first line that raises the error, because Date.parse doesn't know how to handle the string "05/15/2016". Use Date.strptime instead and tell Ruby how to read the string:
DateTime.strptime('05/15/2017', '%m/%d/%Y')
#=> #<DateTime: 2017-05-15T00:00:00+00:00 ((2457889j,0s,0n),+0s,2299161j)>

Related

How to check whether correct date format has been provided

I'm currently working through the Well-Grounded Rubyist and have a question about an exercise that is asking to check whether a date provided is in the format 'yyyy-mm-dd' as opposed to 'yy-mm-dd'.
We have a class Ticket and should create a date= method that checks whether the date provided is in the above mentioned format.
Is .strftime correct to use here?
In the end the method should return the date in the correct format and provide an error message for dates in the wrong format, like so:
ticket = Ticket.new
ticket.date = "2013-11-12"
=> "2013-11-12"
ticket.date = "13-11-12"
=> "Please submit the date in the format 'yyyy-mm-dd'."
Could someone indicate how I could perform these checks on dates?
Date::xmlschema is strict about this specific format (try this in IRB):
require 'date'
Date.xmlschema("2013-11-12") #<Date: 2013-11-12 ((2456609j,0s,0n),+0s,2299161j)>
#invalid month number:
Date.xmlschema("2013-13-12") #<ArgumentError: invalid date>
# 2 digit year:
Date.xmlschema("13-11-12") #<ArgumentError: invalid date>
# no leap year:
Date.xmlschema("2013-02-29") #<ArgumentError: invalid date>
You can throw the error to the user by using begin..rescue
require 'date'
begin
Date.parse("31-02-2010")
rescue => e
p "#{e}" #print your own custom messages and return accordingly
end
Also write
rescue ArgumentError
It will throw By default error
ArgumentError (invalid date)

How to parse different date strings in Ruby

I'm stuck on a question. How to convert the date strings:
["2010/03/30", "15/12/2016", "11-15-2012", "20130720"]
to:
["20100330", "20161215", "20121215", "20130720"]
Most can be parsed with Date.parse. But it doesn't understand all of them.
2.4.4 :013 > Date.parse("11-15-2012")
ArgumentError: invalid date
from (irb):13:in `parse'
from (irb):13
from /Users/schwern/.rvm/rubies/ruby-2.4.4/bin/irb:11:in `<main>'
For any that it doesn't understand you can rescue from the ArgumentError and try your own parsing with strptime.
require 'date'
def parse_date(date)
Date.parse(date)
rescue ArgumentError
Date.strptime(date, '%m-%d-%Y')
end
dates = ["2010/03/30", "15/12/2016", "11-15-2012", "20130720"]
puts dates.map { |date| parse_date(date) }
dates = ["2010/03/30", "15/12/2016", "11-15-2012", "20130720"]
dates = dates.map{|date| date.tr("/-","")} # runs through every string in the array and replaces the stuff

DateTime.strptime can't parse date string

I don't understand why the following Ruby 2.4 code fails:
irb(main):006:0> require 'date'
=> false
irb(main):007:0> fmt = "%-m/%-d/%Y %-l:%M:%S %p"
=> "%-m/%-d/%Y %-l:%M:%S %p"
irb(main):008:0> DateTime.now.strftime(fmt)
=> "1/30/2018 7:42:44 AM"
irb(main):009:0> DateTime.strptime("1/30/2018 7:42:44 AM", fmt)
ArgumentError: invalid date
from (irb):9:in `strptime'
from (irb):9
from /usr/local/bin/irb:11:in `<main>'
irb(main):010:0>
The datetime format works when I format a date, but the same format string fails when I try to parse a date string in that format.
Its because strptime doesn't support the flags in the format you are using, have a look at http://ruby-doc.org/stdlib-2.4.2/libdoc/date/rdoc/DateTime.html#method-c-strptime
The error is because the format fmt you have provided doesn't match the DateTime string you have provided.
Change your format from
fmt = "%-m/%-d/%Y %-l:%M:%S %p"
into
fmt = "%m/%d/%Y %l:%M:%S %p"
Hope this helps.

invalid date using Ruby 1.9.2

Why is 'time' being returned as an invalid date?
val = "9/22/2011 4:23 AM"
time = DateTime.parse(val).strftime("%Y-%m-%d %H:%M:%S").to_datetime
#at breakpoint: time = 2011-09-22T04:23:00+00:00 as a DateTime Object
#form_entry.storage_datetime = time # crashes here with invalid date
If it helps, I'm using gem mysql 2.8.1 and Ruby 1.9.2. Thanks
I got an ArgumentError on line two; couldn't create the DateTime object in the first place.
Try using strptime instead:
val = "9/22/2011 4:23 AM"
DateTime.strptime(val, "%m/%d/%Y %H:%M %p")
=> #<DateTime: 2011-09-22T04:23:00+00:00 (3536390423/1440,0/1,2299161)>

DateTime parse not working as expected

I have Ruby code that looks vaguely like this.
str = 2010-12-02_12-10-26
puts str
puts DateTime.parse(str, "%Y-%m-%d_%H-%M-%S")
I expected to get the actual time from the parse. Instead, I'm getting output like this...
2010-12-02_12-10-26
2010-12-02T00:00:00+00:00
How do I get the time parsed in as well?
This works:
str = "2010-12-02_12-10-26"
puts str
puts DateTime.strptime(str, "%Y-%m-%d_%H-%M-%S")
This example on Codepad.
According to the documentation parse:
Create a new DateTime object by parsing from a String, without specifying the format.
And strptime:
Create a new DateTime object by parsing from a String according to a specified format.
Use strptime instead of parse
puts DateTime.strptime(str, "%Y-%m-%d_%H-%M-%S")

Resources