I have a date (Which is actually parsed from a PDF) and it could be any of the following format:
MM/DD/YYYY
MM/DD/YY
M/D/YY
October 15, 2007
Oct 15, 2007
Is there any gem or function available in rails or ruby to parse my date?
Or I need to parse it using regex?
BTW I'm using ruby on rails 3.2.
You can try Date.parse(date_string).
You might also use Date#strptime if you need a specific format:
> Date.strptime("10/15/2013", "%m/%d/%Y")
=> Tue, 15 Oct 2013
For a general solution:
format_str = "%m/%d/" + (date_str =~ /\d{4}/ ? "%Y" : "%y")
date = Date.parse(date_str) rescue Date.strptime(date_str, format_str)
I find the chronic gem very easy to use for time parsing and it should work for you. i tried the examples you gave.
https://github.com/mojombo/chronic
Related
App uses SOAP4r for consuming API/SOAP
But SOAP::SOAPTimeFormat is returning
2015-11-15T16:59:521468.7999999999999545-04:00
chkout.add('purchasedDt ', SOAP::SOAPDateTime.new(basket.purchase_Date))
Using strftime('%Y-%m-%dT%H:%M:%S') is giving the following
chkout.add('purchasedDt ', SOAP::SOAPDateTime.new(basket.purchase_Date.strftime('%Y-%m-%dT%H:%M:%S')))
2015-11-15T16:59:52Z
What App needs is
2015-11-15 16:59:52 -0400
Please advise ...need the format in
yyyy-mm-ddThh:mm:ss-/+gmt
-Fransis
A simple change in your strftime and you can find out more in the doc for Time#strftime
basket.purchase_Date.now.strftime('%Y-%m-%d %H:%M %z')
=> "2016-04-26 22:48 -0400"
Seems like your applicaton accepts the iso8601 format. You can use Time#xmlschema as a shortcut to generate iso8601 compatible strings:
basket.purchase_Date.xmlschema
#=> "2015-11-15T16:59:52-04:00"
Just change this line in your example:
chkout.add('purchasedDt ', SOAP::SOAPDateTime.new(basket.purchase_Date.xmlschema))
I have two valid URL's to two images.
When I run open() on the first URL, it returns an object of type Tempfile (which is what the fog gem expects to upload the image to AWS).
When I run open() on the second URL, it returns an object of type StringIO (which causes the fog gem to crash and burn).
Why is open() not returning a Tempfile for the second URL?
Further, can open() be forced to always return Tempfile?
From my Rails Console:
2.2.1 :011 > url1
=> "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/c0.0.448.448/10298878_10103685138839040_6456490261359194847_n.jpg?oh=e2951e1a1b0a04fc2b9c0a0b0b191ebc&oe=56195EE3&__gda__=1443959086_417127efe9c89652ec44058c360ee6de"
2.2.1 :012 > url2
=> "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/c0.17.200.200/1920047_10153890268465074_1858953512_n.jpg?oh=5f4cdf53d3e59b8ce4702618b3ac6ce3&oe=5610ADC5&__gda__=1444367255_396d6fdc0bdc158e4c2e3127e86878f9"
2.2.1 :013 > t1 = open(url1)
=> #<Tempfile:/var/folders/58/lpjz5b0n3yj44vn9bmbrv5180000gn/T/open-uri20150720-24696-1y0kvtd>
2.2.1 :014 > t2 = open(url2)
=> #<StringIO:0x007fba9c20ae78 #base_uri=#<URI::HTTPS https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/c0.17.200.200/1920047_10153890268465074_1858953512_n.jpg?oh=5f4cdf53d3e59b8ce4702618b3ac6ce3&oe=5610ADC5&__gda__=1444367255_396d6fdc0bdc158e4c2e3127e86878f9>, #meta={"last-modified"=>"Tue, 25 Feb 2014 19:47:06 GMT", "content-type"=>"image/jpeg", "timing-allow-origin"=>"*", "access-control-allow-origin"=>"*", "content-length"=>"7564", "cache-control"=>"no-transform, max-age=1209600", "expires"=>"Mon, 03 Aug 2015 22:01:40 GMT", "date"=>"Mon, 20 Jul 2015 22:01:40 GMT", "connection"=>"keep-alive"}, #metas={"last-modified"=>["Tue, 25 Feb 2014 19:47:06 GMT"], "content-type"=>["image/jpeg"], "timing-allow-origin"=>["*"], "access-control-allow-origin"=>["*"], "content-length"=>["7564"], "cache-control"=>["no-transform, max-age=1209600"], "expires"=>["Mon, 03 Aug 2015 22:01:40 GMT"], "date"=>["Mon, 20 Jul 2015 22:01:40 GMT"], "connection"=>["keep-alive"]}, #status=["200", "OK"]>
This is how I'm using fog:
tempfile = open(params["avatar"])
user.avatar.store!(tempfile)
I assume you are using Ruby's built-in open-uri library that allows you to download URLs using open().
In this case Ruby is only obligated to return an IO object. There is no guarantee that it will be a file. My guess is that Ruby makes a decision based on memory consumption: if the download is large, it puts it into a file to save memory; otherwise it keeps it in memory with a StringIO.
As a workaround, you could write a method that writes the stream to a tempfile if it is not already downloaded to a file:
def download_to_file(uri)
stream = open(uri, "rb")
return stream if stream.respond_to?(:path) # Already file-like
Tempfile.new.tap do |file|
file.binmode
IO.copy_stream(stream, file)
stream.close
file.rewind
end
end
If you're looking for a full-featured gem that does something similar, take a look at "down": https://github.com/janko-m/down
The open uri library has 10K size limit for choose either StringIO or Tempfile.
My suggestion for you is change to constant OpenURI::Buffer::StringMax, that used for open uri set default
In your initializer you could make this:
require 'open-uri'
OpenURI::Buffer.send :remove_const, 'StringMax' if OpenURI::Buffer.const_defined?('StringMax')
OpenURI::Buffer.const_set 'StringMax', 0
This doesn't answer my question - but it provides a working alternative using the httparty gem:
require "httparty"
File.open("file.jpg", "wb") do |tempfile|
tempfile.write HTTParty.get(params["avatar"]).parsed_response
user.avatar.store!(tempfile)
end
I have been using local_time to convert servertime to client local time. However now I am using datatables and to sort date/time columns. I have to use date-moment.js plugin of Datatables which uses moment.js to handle date conversions.
My problem is: the local_time's view helper is wrapping the date with < time > tag like this
<time data-format="%B %e, %Y %l:%M%P"
data-local="time"
datetime="2013-11-27T23:43:22Z"
title="November 27, 2013 6:43pm EDT"
data-localized="true">November 27, 2013 6:43pm</time>
The wrapping thing is creating problem for moment.js to get the actual date-time as it expects. I need it to convert the date-time but not wrap with <time> tag. Is it possible. If yes How?
currently created a helper method to extract the core date from the string returned by the gem's local_date method
in views/
<%= extract_date(local_date(workflow.created_at, CommonConstants::DATE_FORMAT_LONG)) %>
# Parse the string generated by local_time gem
# Expectation :
# "<time data-format=\"%B %e, %Y\" data-local=\"time\" datetime=\"2015-10-28T11:19:54Z\">October 28, 2015</time>"
def extract_date(date_string)
date_string.split('>').pop.split('</')[0] rescue ''
end
What I would like to do is to go from "2013", "December", "20" and to create 2013-12-20.
Does someone have an idea ? Thanks !
Rails provide nice converters in part of it's framework
2.1.2 :001 > "20 december 2013".to_date
=> Fri, 20 Dec 2013
For your required format you can use this bit for formatting:
strftime("The date is %y-%m-%d")
This can be called on any time object.
You can do this:
Date.new(2013, 12, 20)
You can read more about Date here
This is an extension to #Marc-Alexandre Bérubé 's answer to get your desired format:
"20 december 2013".to_date.strftime("%Y-%m-%d")
# => "2013-12-20"
saving a string to my db as a date and having some strange results
if the date is formatted like,
dd/mm/yy it will save
if date is formatted like,
mm/dd/yy it will fail to save silently
in my console if i go
'20/10/2012'.to_date
=> Sat, 20 Oct 2012
it works
if i go
'10/20/2012'.to_date
=> ArgumentError: invalid date ...
it breaks
i used an initializer to set up my default date format to %m/%d/%Y which you can see is accurately reflected in my DATE_FORMATS hash.
Date::DATE_FORMATS
=> {:short=>"%e %b", :long=>"%B %e, %Y", :db=>"%Y-%m-%d", :number=>"%Y%m%d", :long_ordinal=>#<Proc:0x007f8663f1aae0#/Users/ian/.rvm/gems/ruby-1.9.3-p0#rails-3.2/gems/activesupport-3.2.1/lib/active_support/core_ext/date/conversions.rb:12 (lambda)>, :rfc822=>"%e %b %Y", :default=>"%m/%d/%Y"}
Uncertain what is the cause of the issue here, as things seem to be configured correctly. How to resolve?
thank you!
Try:
DateTime.strptime('20/10/2012', '%d/%m/%Y')
Or just use Date if you don't need an associated time:
Date.strptime('20/10/2012', '%d/%m/%Y')
Use gem american_date
In gem file
gem 'american_date'
Now it will save mm/dd/yyyy date format.