Chrillewoodz
Chrillewoodz

Reputation: 28338

Date conversion is not working as expected, time always remains after conversion

I'm trying to do the most simple of things, convert a date to a different date format but I can't seem to do it as my knowledge in ruby is practically zero.

I tried to read through this and tried all of the possible .to_formatted_s() versions but none of them works. The time seems to always remain there no matter what. Since this date doesn't come from a date.new() but rather an existing object property I'm guessing this is the reason why .to_formatted_s() isn't working as in the example in the docs. I could be horribly wrong though.

How do I convert this date format:

2015-07-01 01:59:59 +0200

To this:

2015-07-01

My attempts were:

  // inv.end is "2015-07-01 01:59:59 +0200"

  inv.end.to_formatted_s(:db)
  inv.end.to_s(:db)
  inv.end.to_formatted_s(:iso8601)

Which all outputted 2015-06-30 23:59:59.

What am I doing wrong?

Upvotes: 0

Views: 20

Answers (2)

Chakreshwar Sharma
Chakreshwar Sharma

Reputation: 2610

The above answer is correct.
If you want to perform the same date format repetitively , then create a file in initializers & write the below code:
class ActiveSupport::TimeWithZone
def my_format(options = {})
strftime('%m-%d-%Y')
end
end

& after the datetime object just write my_format like @user.updated_at.my_format

Upvotes: 1

max
max

Reputation: 102222

require 'date'
DateTime.parse("2015-07-01 01:59:59 +0200").strftime('%Y-%m-%d')

Upvotes: 1

Related Questions