Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Get the time from a datetime

If I have a datetime value of something like 1/10/2011 9:00:00, how do I get the 9:00 am from that datetime?

like image 223
Jhorra Avatar asked Jul 22 '11 06:07

Jhorra


People also ask

How do you parse time in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.

What does DateTime now return in Ruby?

DateTime#now() : now() is a DateTime class method which returns a DateTime object denoting the given calendar date. Return: DateTime object denoting the given calendar date.

Is it possible to use date class in rails?

For most cases, the Time with the time zone class from Rails’ ActiveSupport is sufficient. But sometimes, when you just need a string format of year, month and day, Dateclass still worth a try. Remember to add require 'date'when you encounter undefined methoderror, when trying to use Dateclass.

What is the difference between date and DateTime in Ruby?

Date and DateTime classes are both from date library. And Time class from its own time library. Tech Notes from Steven Home About Date, Time, DateTime in Ruby and Rails Mar 23, 2013• Steven Yue There are 3 different classes in Ruby that handle date and time. Dateand DateTimeclasses are both from datelibrary. And Timeclass from its own timelibrary.

How do you handle date and time in Ruby?

There are 3 different classes in Ruby that handle date and time. Date and DateTime classes are both from date library. And Time class from its own time library. Tech Notes from Steven

How do I set the time zone in rails?

For Rails application, you can set the default time zone under /config/application.rb # /config/application.rbconfig.time_zone='Central Time (US & Canada)' To get a list of time zone names supported by Rails, you can use ActiveSupport::TimeZone.zones_map(&:name)


2 Answers

strftime will do it.

t = Time.now t.strftime("%I:%M%p") 

All other attributes here:

http://www.wetware.co.nz/blog/2009/07/rails-date-formats-strftime/

like image 132
Chris Barretto Avatar answered Oct 06 '22 03:10

Chris Barretto


DateTime.new(2011,10,1,9).to_s(:time) #=> "09:00"  DateTime.now.to_s(:time) #=> "11:58" 

From Time docs

like image 21
Eyal Levin Avatar answered Oct 06 '22 03:10

Eyal Levin