current_user
current_user

Reputation: 1212

converting string attributes into date and time format

I have two model attributes called "date" and "time" that are strings:

004 > Event.first.date
  => "21/12/2019"
005 > Event.first.time
  => "7:30 PM"

I want to display the date and time of the event in the show page as:

Saturday, December 21 7:30 PM

My ruby version is 2.6.3.

Upvotes: 0

Views: 242

Answers (4)

Enrico Cortinovis
Enrico Cortinovis

Reputation: 861

If you store your date and time in a single variable like this

Tue, 10 Aug 2010 01:20:19 -0400 (EDT)

You can use the very handy Date.parse() function:

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10

This is probably the simplest method to convert a string to a date.

Upvotes: 0

lacostenycoder
lacostenycoder

Reputation: 11226

You can use DateTime.strptime:

date = Event.first.date
time = Event.first.time
dt = DateTime.strptime("#{date} #{time}", "%d/%m/%Y %l:%M %p")

So in your view:

dt.strftime("%A, %B, %d %l:%M %p")

Upvotes: 1

The Wizard
The Wizard

Reputation: 953

You should have a look at the strftime method provided in Ruby.

You already have the time you would like to display, to get the date in your format you need to provide the following directives to strftime:

  1. %A - Gives the full weekday name, for example "Sunday".
  2. %B - Gives the full month name, for example "December".
  3. %d - Gives the day of the month, zero-padded for example 09

Combining these together you should be able to do the following:

  > "#{Date.parse(Event.first.date).strftime('%A, %B %d')} #{Event.first.time}"
  => "Saturday, December 21 7:30 PM"

Once again all the information on strftime is available in the documentation.

Upvotes: 3

Cary Swoveland
Cary Swoveland

Reputation: 110725

require 'time'

date_str = "21/12/2019"
time_str = "7:30 PM"

Step 1: Use DateTime::strptime to convert strings to a DateTime object

dt = DateTime.strptime(date_str + time_str, '%d/%m/%Y%H:%M %p')
  #=> #<DateTime: 2019-12-21T19:30:00+00:00 ((2458839j,70200s,0n),+0s,2299161j)>

Step 2: Use DateTime::strftime to convert the DateTime object to the desired string

dt.strftime("%A, %B %d %l:%m %p") 
  #=> "Saturday, December 21  7:30 PM"

Note:

DateTime.parse("I never use DateTime::parse, Data::parse or Time::parse " +   
               "because you never know what you may get")
  #=> #<DateTime: 2019-05-01T00:00:00+00:00 ((2458605j,0s,0n),+0s,2299161j)>

Use strptime!

Upvotes: 2

Related Questions