Ruby Regex extract parameters - ruby-on-rails

I have a date in this format
11/28/2011 2:39:00 PM
I cant seem to get a way to extract to each element out of this format (like take out day, month, year, hour, minute, second, AM/PM) separately to work with them. I need help here, so i can use this to rearrange the time manually and work with it how i want. I cant find a solution for this. (but im pretty sure i would need to use regex)

require 'date'
str = '11/28/2011 2:39:00 PM'
date = DateTime.strptime(str, '%m/%d/%Y %I:%M:%S %p')
puts date.year # etc

Though I'm sure regex isn't the best way to do it, here are some regex's that I tested on rubular.com!
Month:
(\d){2}(?=\/\d\d\/)
Day:
(\d){2}(?=\/\d\d\d\d)
Year:
(\d){4}(?=\s)
Hour:
(\d){1,2}(?=:\d\d:\d\d\s)
Minute:
(\d){2}(?=:\d\d\s)
Second:
(\d){2}(?=\s\w\w\b)
AM/PM:
\b[PA]M\b

I've found it easiest to use the Chronic gem to do this kind of parsing. Chronic handles these a lot better than the default DateTime stuff:
gem install chronic
And then:
require 'chronic'
date = Chronic.parse(my_date)
puts "year, month, day, hour: #{date.year}, #{date.month}, #{date.day}, #{date.hour}"
Etc.

You don't have to parse it with regular expression, you can simply convert into DateTime:
require 'date'
my_time = DateTime.parse('11/28/2011 2:39:00 PM')
puts my_time.day # and so on

You can use DateTime.strptime http://ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html#method-c-strptime to create a DateTime object and use that.

You can use this naive regex:
/(\d+)/(\d+)/(\d+)\s(\d+):(\d+):(\d+)\s(\w+)/
If your format never changes, ever, at all...

Related

Ruby - Convert Day Of Week To Integer

How would you convert a day string (i.e. "Monday" or "Wednesday"), into the corresponding wday integer (1 or 3)?
I've come up with this convoluted way
Date.today.beginning_of_week("Monday".downcase.to_sym).wday
You can parse it using strptime:
Date.strptime('Monday', '%A').wday
#=> 1
Date.strptime('Wednesday', '%A').wday
#=> 3
The intermediate date object refers to the weekday in the current week:
Date.today
#=> #<Date: 2018-11-20 ...>
Date.strptime('Monday', '%A')
#=> #<Date: 2018-11-19 ...>
You can also use _strptime (prefixed with an underscore) to extract the date elements which happen to be :wday for a single weekday:
Date._strptime('Monday', '%A')
#=> {:wday=>1}
You can use the CHRONIC gem.
Chronic is a Ruby natural language date/time parser written by Tom
Preston-Werner (#mojombo) which takes surprisingly human readable text
and converts it to dates. (http://robdodson.me/playing-with-ruby-dates/)
You can use like this:
require 'chronic'
Chronic.parse('Monday').wday
=> 1
I hope help you!

Extend strftime directives to format a time like "tomorrow at 14:00"

I've found the list of format directives for the strftime method http://ruby-doc.org/core-2.3.0/Time.html#method-i-strftime
There are various options to format a time like weekdays, day of month... But I'm interested in formating a Time like
Time.parse("2016-02-30T12:24").strftime("%XXX, at %H:%M")
# => tomorrow at 12:24
Here %XXX should be "today", "yesterday", "tomorrow", "in 2 days" or "in 3 days".
Is it possible to extend the directives of strftime so that I can use my own placeholder?
I think following distance_of_time_in_words helper would help.
http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words
You can use Rails Distance of Time in Words which will give you 'about 1 day' but I think it would be easier to use MomentJS's Calendar Time.
Calendar Time will help you return something like " Tomorrow at 2:30 AM"

Reformat date Rails 4

Looking for the best way to convert a string like "01/16/2016" into a friendly date format that rails can handle.
I have a calendar in which users can select a from_date and a to_date.. based on those params, my search will then filter results that fit the time periods.
Unfortunately, rails cannot handle the current format its in. Not sure the best way to go about this. I could change the search form's javascript to display the date differently, but I feel this format is most user friendly.
thx!
You can use the standard ruby Date class:
some_date = Date.strptime('01/16/2016', '%m/%d/%Y')
some_date will be an instance of Date, which then you can handle in rails and reformat in any way you want using strftime.
As like taglia said you can use the strptime
Date.strptime('01/16/2016', '%m/%d/%Y')
You can change the calendar date format from dd/mm/yyyy to mm/dd/yyyy, then you can use
require 'date'
date = DateTime.parse("16/01/2016")
=> #<DateTime: 2016-01-16T00:00:00+00:00 ((2457404j,0s,0n),+0s,2299161j)>
date.strftime('%a %b %d %H:%M:%S %Z %Y')
=> "Sat Jan 16 00:00:00 +00:00 2016"
You can use Date instead of DateTime if you want only the date.

Rails issue with parsing date

I have datetime strings that are outputted in the following format:
03/27/2014 07:52:47 PM
I'm using a gem called rufus-scheduler, which takes strings in a YYYY-mm-dd hh-MM-ss #### (#### is timezone offset). Are there any easy ways to convert the first string I had to a string in the format rufus-scheduler likes?
I know that one way I could do it would be to create a method that parsed the string so I could create a new datetime object from it, and then call a strftime in the format rufus likes, but I was wondering if there were any more efficient ways to go about solving my problem.
You can use DateTime::strptime to parse, and DateTime#strftime to format it again.
First require 'date' and then:
2.0.0-p451 :021 > DateTime.strptime("03/27/2014 07:52:47 PM", "%m/%d/%Y %H:%M:%S %p").strftime("%Y-%m-%d %H-%M-%S %z")
=> "2014-03-27 19-52-47 +0000"
Check out Time.strftime
Also, http://www.foragoodstrftime.com/ is an awesome tool for this.
Chronic (https://github.com/mojombo/chronic) is your friend
require 'chronic'
p Chronic.parse('03/27/2014 07:52:47 PM')

Convert 2 types of date strings to datetime objects

I need a reliable way to convert formatted date strings into datetime objects so I can save into the database. I'm importing data from an RSS feed and the date strings look like this 10/31/2012 11:59:00 PM, but every once in a while one will come through with no time data, like this: 9/24/2012. Is there a way to convert the string to a datetime object regardless if the time is present or not?
I was using Date.strptime() because Date.parse() wasn't being reliable enough for me. Here's what I was using, which will error out when it encounters the date string without the time.
Date.strptime(i.xpath('activedate').text, '%m/%d/%Y %I:%M:%S %p').to_datetime
What would be the best way to handle this?
I recommend chronic:
require 'chronic'
Chronic.parse '10/31/2012 11:59:00 PM'
#=> 2012-10-31 23:59:00 0800
Chronic.parse '9/24/2012'
#=> 2012-09-24 12:00:00 0800
I'd just loop through an array of the possible date formats and try parsing until one succeeds:
parsed_date = nil
['%m/%d/%Y %I:%M:%S %p', '%m/%d/%Y'].each do |format|
parsed_date ||= DateTime.strptime(i.xpath('activedate').text, format) rescue nil
end

Resources