Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set time part of DateTime in ruby

Tags:

datetime

ruby

Say I have a datetime object eg DateTime.now. I want to set hours and minutes to 0 (midnight). How can I do that?

like image 254
Jesse Aldridge Avatar asked Jun 13 '11 06:06

Jesse Aldridge


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.


2 Answers

Within a Rails environment:

Thanks to ActiveSupport you can use:

DateTime.now.midnight DateTime.now.beginning_of_day 

OR

DateTime.now.change({ hour: 0, min: 0, sec: 0 })  # More concisely DateTime.now.change({ hour: 0 })                 

Within a purely Ruby environment:

now = DateTime.now DateTime.new(now.year, now.month, now.day, 0, 0, 0, now.zone) 

OR

now = DateTime.now DateTime.parse(now.strftime("%Y-%m-%dT00:00:00%z")) 
like image 112
ashoda Avatar answered Sep 19 '22 11:09

ashoda


Nevermind, got it. Need to create a new DateTime:

DateTime.new(now.year, now.month, now.day, 0, 0, 0, 0) 
like image 39
Jesse Aldridge Avatar answered Sep 20 '22 11:09

Jesse Aldridge