S_A S_A - 3 months ago 5
Ruby Question

How can I change the day in a date string?

I have a string variable with a date like this:

@date = "2016-09-01"


And I have another variable with a day like this:

@day = 5


How can I change the day of the date using
@day
value?

I need this result:

@date = "2016-09-05"

Answer

If you just want to work with the plain string, you can just replace the last 2 characters from the date string like this:

@date[-2..-1] = @day.to_s.rjust(2, "0")
Comments