How to Format a Date to Mm/Dd/Yyyy in Ruby

How do I format a date to mm/dd/yyyy in Ruby?

The strftime method can be used to format times:

Time.now.strftime("%m/%d/%Y")

How to change date format from mm/dd/yyyy to dd/mm/yyyy Ruby on Rails

Two steps:

  • You need to convert your string into Date object. For that, use Date#strptime.
  • You can use Date#strftime to convert the Date object into preferred format.

See implementation below:

str = '01/14/2018'

date = Date.strptime(str, '%m/%d/%Y')
=> #<Date: 2018-01-14 ((2458133j,0s,0n),+0s,2299161j)>

date.strftime('%d-%m-%Y')
=> "14-01-2018"

date.strftime('%Y-%m-%d')
=> "2018-01-14"

Formatting Date/Time in Ruby to YYYY-MM-DD HH:MM:SS

You can use the Time#strftime method to format the time into a variety of different formats, including the one which you need. It takes a parameter which specifies the format of the date output. Look at the documentation for this method for more instructions about how to use it.

Time.now.strftime("%F %T")

The %F specifies that we would like the date in YYYY-MM-DD format. This is followed by a space, then the %T specifier, which produces a HH:MM:SS time output.

To incorporate this into your code:

"erstellzeit": "#{Time.now.strftime("%F %T")}"

Alternatively, if you're getting an additional +0000 output, try:

"erstellzeit": "#{Time.now.strftime("%F %H:%M:%S")}"

Ruby convert DD/MM/YYYY string to YYYY,MM,DD

What about?

def reformat_date(str)
str.split('/').reverse.join(',')
end

How to display the current date in mm/dd/yyyy format in Rails

<%= Time.now.strftime("%m/%d/%Y") %>

Rails datetime format dd/mm/yyyy

For reading you can use strptime and specify the format:

datetime = "14/04/17 07:00"
DateTime.strptime(datetime, "%d/%m/%y %R")
=> Wed, 14 Apr 0017 07:00:00 +0000

Explanation

%d - Day of the month, zero-padded (01..31)
%m - Month of the year, zero-padded (01..12)
%y - year % 100 (00..99)
%R - 24-hour time (%H:%M)

For getting the date you can transform DateTime objects to Date objects using to_date or use .strftime("%d/%m/%Y") directly on DateTime to get String.

[47] pry(main)> a
=> Fri, 14 Apr 2017 07:00:00 +0000
[48] pry(main)> a.to_date
=> Fri, 14 Apr 2017
[49] pry(main)> a.strftime("%d/%m/%Y")
=> "14/04/2017"
[50] pry(main)> a.strftime("%R")
=> "07:00"

Full docs here. Also a full list of format directives is available on strftime docs

How to display date of birth in dd-mm-yyyy format in Ruby

To modify the format of the date of birth in your view, you can use strftime:

<div class="col-md-10 primary-info-label"> 
<label><%= @user.date_of_birth.strftime("%d-%m-%Y") %></label>
</div>

The above should format the date_of_birth to be in mm-dd-yyyy format. More info on strftime here.

Hope it helps!

ruby DateTime parsing from 'mm/dd/yyyy' format

require 'date'
my_date = Date.strptime("12/22/2011", "%m/%d/%Y")


Related Topics



Leave a reply



Submit