简体   繁体   中英

Rails datetime format “dd/mm/yyyy”

I receive dates like "14/04/17 07:00"

I want to get only the date like this: 14/04/2017

And only the hour 07:00

I tried this way, BTW I know it's for US time, it render me 17/04/10

DateTime.parse(datetime).strftime("%d/%m/%Y")

Humm I can't find anywhere how to do this?

Thanks for your help

EDIT

with the suggestion:

my_date = DateTime.parse(datetime).strftime("%d/%m/%Y")

If I do in my terminal:

[1] pry(main)> O = Onduleur.last
  Onduleur Load (0.2ms)  SELECT  "onduleurs".* FROM "onduleurs" ORDER BY "onduleurs"."id" DESC LIMIT ?  [["LIMIT", 1]]
=> #<Onduleur:0x007fa6b70186e0
 id: 144,
 identifier: 2,
 datetime: "11/04/17 23:00",
 energy: 0,
 created_at: Wed, 12 Apr 2017 15:17:04 UTC +00:00,
 updated_at: Wed, 12 Apr 2017 15:17:04 UTC +00:00>
[2] pry(main)> my_date = DateTime.parse(O.datetime).strftime("%d/%m/%Y")
=> "17/04/2011"
[3] pry(main)>

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

You can set to variables with the desire data

datetime = "2017-04-12 10:30:14"

my_date = DateTime.parse(datetime).strftime("%d/%m/%Y")
my_hour = DateTime.parse(datetime).strftime("%H:%M")

puts my_date
puts my_hour

Output:

12/04/2017
10:30

EDIT:

If you have this format date ( 11/04/2017 23:00 ), you can try with .to_time method

require 'active_support/core_ext/string'

datetime2 = "11/04/2017 23:00".to_time

my_date2 = datetime2.strftime("%d/%m/%Y")
my_hour2 = datetime2.strftime("%H:%M")

puts my_date2
puts my_hour2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM