I am pretty familiar with strptime in Rails, but I cannot get this date to format. The date is coming from a long .csv file so it would be a pain to pre-format the dates differently.
date = "2/9/17"
Date.strptime(date, "%-m/%-d/%y")
ArgumentError: invalid date
From the strptime documentation:
strptime does not support specification of flags and width unlike strftime
So you need a slightly simplified pattern:
date = "2/9/17"
Date.strptime(date, "%m/%d/%y")
# => #<Date: 2017-02-09 ((2457794j,0s,0n),+0s,2299161j)>
Date.strptime(date, "%m/%d/%y")?
Related
I've got date as string '2020-02-10 8,00' which I want to convert into Monday, 10th of February. I'm aware of this old topic however I cannot find (or use) any related information.
All I have is just parsed string to date - Date.parse '2020-02-10 8,00'
You are halfway there! Date.parse '2020-02-10 8,00' produces a ruby Date object, as you have noted. You now have to apply strftime. However strftime doesn't have any ordinalization so that piece has to be done manually.
date = Date.parse('2020-02-10 8,00')
date.strftime("%A, #{date.day.ordinalize} of %B") #=> Monday, 10th of February
the ordinalize method is provided by ActiveSupport.
If this format will be used multiple times in your app, you may wish to add an app-wide format:
# in config/initializers/time_formats.rb
Date::DATE_FORMATS(:ordinalized_day) = lambda{|date| date.strftime("%A, #{date.day.ordinalize} of %B")}
# anywhere in the app
Date.today.to_formatted_s(:ordinalized_day)
In my rails app, I have the following configuration for date formats:
config/initializers/time_formats.rb
Date::DATE_FORMATS[:concise] = "%d/%b/%Y"
Time::DATE_FORMATS[:concise] = "%d/%b/%Y %H:%M %Z"
In my view, if I do:
MODEL.created_at.to_formatted_s(:concise)
... it correctly picks-up the :concise format for the datetime date type, and renders it as follows:
13/Oct/2020 05:00 UTC
Note that the %b is the short Month name - Oct in this case. If I only want to show the date, I would assume that I'd simply use the to_date method to convert the datetime to a date first:
MODEL.created_at.to_date.to_formatted_s(:concise)
This does render a date, but it doesn't pick up the :concise date format properly. It renders:
13/10/2020
Note it's not rendering October as 10, instead of formatting as %b. I've tried adding a :default date type in time_formats.rb but that didn't fix it.
Why is this happening just for the Date type?
(I'm using ruby 2.5.8, Rails 6.)
I need to convert a string that represents a date to a timestamp object in Ruby.
For example:
date_string = "18-Feb-2016 09:01:04"
convert to a timestamp like so
2016-02-18 14:01:04
I need to save this to a mysql database were the column is type timestamp.
I have researched this for most of the day and can not find a solution. I know you can use Time.parse but that includes timezone and DateTime.parse().to_time includes the timezone. Since it has to be a timestamp i can not use strftime method.
I need the time to be included because it will be used for calculation purposes.
Any help would be greatly appreciated.
Thank you
TL;DR
datetime = DateTime.parse("18-Feb-2016 09:01:04").to_s(:db)
returns
"2016-02-18 09:01:04"
Here's a quick explanation...
1. Convert your string to a Date object with DateTime.parse
You can use the .parse method from the Date or DateTime class in order to parse a string. The parse method will return a Date object like this:
$ DateTime.parse("18-Feb-2016 09:01:04")
$ => #<DateTime: 2016-02-18T09:01:04+00:00 ((2457437j,32464s,0n),+0s,2299161j)>
.parse is a method provided by Ruby.
2. Format the string with DateTime.parse.to_s
Ruby on Rails gives you access to the DateTime.to_formatted_s method to change the formatting of the Date object prior to storing it in your database.
To match the format that you specified:
$ datetime = DateTime.parse("18-Feb-2016 09:01:04").to_formatted_s
Note: to_s is aliased from to_formatted_s and to_formatted_s is a method provided by Rails, not Ruby.
Use to_datetime method in Rails.
"12-10-2015".to_datetime
=> Mon, 12 Oct 2015 10:36:00 +0000
http://apidock.com/rails/String/to_datetime
Edited to add precise answer.
You can use .to_time or .to_datetime, the .to_time returns the date and time with timezone but the .to_datetime returns full date with week name but it shows +0000 as timezone, you will see the difference in both the formats, see the following example.
# used .to_time
"18-Feb-2016 09:01:04".to_time
## Output
2016-02-18 09:01:04 +0530
# used .to_datetime
"18-Feb-2016 09:01:04".to_datetime
## Output
Thu, 18 Feb 2016 09:01:04 +0000
I've interpreted the question to be that you wish to convert the string "18-Feb-2016 09:01:04" to the string "2016-02-18 14:01:04" (generalized to arbitrary date-time strings, of course).
Let:
str = "18-Feb-2016 09:01:04"
What you want is done in two steps. The first is to convert this string to a DateTime object, that is, an instance of the class DateTime. The second step is to construct the desired string from the DateTime object.
One way to create the DateTime object is to use the method DateTime::parse:
require 'date'
DateTime.parse(str)
#=> #<DateTime: 2016-02-18T09:01:04+00:00 ((2457437j,32464s,0n),+0s,2299161j)>
That works fine for the string format you gave, but can be problematic with other formats. For example:
DateTime.parse "4-5-16 09:01:04"
#=> #<DateTime: 2004-05-16T09:01:04+00:00 ((2453142j,32464s,0n),+0s,2299161j)>
As long as you know the format that will be used, it's generally better to use DateTime#strptime with the appropriate pattern comprised of format directives:
pattern = "%d-%m-%y %H:%M:%S"
DateTime.strptime("4-5-16 09:01:04", pattern)
#=> #<DateTime: 2016-05-04T09:01:04+00:00((2457513j,32464s,0n),+0s,2299161j)>
See DateTime#strftime for the format directives.
For the problem at hand:
dt = DateTime.strptime(str, "%d-%b-%Y %H:%M:%S")
#=> #<DateTime: 2016-02-18T09:01:04+00:00 ((2457437j,32464s,0n),+0s,2299161j)>
The second step is to construct the desired string with the above-referenced strftime method:
dt.strftime("%Y-%m-%d %H:%M:%S")
#=> "2016-02-18 09:01:04"
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.
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')