Home > Enterprise >  How to extract time from DateTime to have access to only the time in Ruby on Rails application
How to extract time from DateTime to have access to only the time in Ruby on Rails application

Time:06-12

I am trying to extract the time from a DateTime example 2022-02-26 10:00:00 UTC I want to return only the 10:00:00 from it. Please help Using Rails v.6

CodePudding user response:

By using strftime method and passing "%H:%M:%S" format to it

%H - Hour of the day, 24-hour clock, zero-padded (00..23)
%k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
%I - Hour of the day, 12-hour clock, zero-padded (01..12)

%M - Minute of the hour (00..59)

%S - Second of the minute (00..59)

%P - Meridian indicator, lowercase (``am'' or ``pm'')
%p - Meridian indicator, uppercase (``AM'' or ``PM'')
date = DateTime.now
date.strftime("%H:%M:%S")

# Output 07:44:10

Or if you need to have all segment separately you can extract hours, minutes and seconds like this:

date = DateTime.now

hour = date.hour # 07
minute = date.minute # 44
second = date.second # 10

# and you can interpolate
time = "#{hour}:#{minute}:#{second}"
  • Related