Waqas Ahad
Waqas Ahad

Reputation: 95

How to save time along with user enter date in timestamp in rails

Using timestamp for date and time saving.User enter only date, I want that before save time also append along with this.

By default timestamp add time 00:00:00

["end_date", "2015-11-30 00:00:00"]

I want that I add time 23:59:59 and it looks like this

["end_date", "2015-11-30 23:59:59"]

Upvotes: 0

Views: 67

Answers (2)

Marcin Urbanski
Marcin Urbanski

Reputation: 2493

pry(main)> Date.parse("2015-11-30").beginning_of_day.to_s
=> "2015-11-30 00:00:00 -0800"

pry(main)> Date.parse("2015-11-30").end_of_day.to_s
=> "2015-11-30 23:59:59 -0800"

Upvotes: 2

Sachin Gevariya
Sachin Gevariya

Reputation: 1167

You should use this in model

before_create :set_end_date

def set_end_date
   "#{self.end_date} 00:00:00".to_time.to_formatted_s(:db)
end

You will get response like this: 2015-11-30 00:00:00

If you add 23:00:00 then use this:

"#{self.end_date} 23:59:59".to_time.to_formatted_s(:db)

then you will get response like: 2015-11-30 23:59:59

For more formatting, you should refer this document.

Upvotes: 0

Related Questions