2

I'm trying to parse a specific hour of a specific date. When I put the date directly as an argument, it works fine, but when I create a variable and put it in the argument it returns the current date.

Why is that?

NOTE: the variable time is 9pm and I need to parse 9pm of 12 March 2016.

datetime = DateTime.new(2016,3,12,9)
=> Sat, 12 Mar 2016 09:00:00 +0000

DateTime.parse("sat 12 march 2016 9pm")
=> Sat, 12 Mar 2016 21:00:00 +0000

DateTime.parse("datetime 9pm")
=> Mon, 14 Mar 2016 21:00:00 +0000
5
  • Where is hour variable? Commented Mar 14, 2016 at 12:34
  • I meant variable time! Commented Mar 14, 2016 at 12:36
  • "the variable hour is 9am 12 March" - that looks like an hour, a day and a month. What's the variable part and what's the fixed part? Commented Mar 14, 2016 at 13:04
  • 1
    BTW, you should probably use Time (or Rails' TimeWithZone) instead of DateTime Commented Mar 14, 2016 at 13:13
  • Very good point! thank you Commented Mar 14, 2016 at 13:18

2 Answers 2

7

In your third call, you use the literal string "datetime" rather than the value of your datetime variable. You can use string interpolation to use the variable's value:

DateTime.parse("#{datetime} 9pm")

In this case, the "9pm" is ignored since it doesn't make sense added to the end of an existing date but this is why the initial attempt wasn't working. Interpolation is generally a solution for using a variable's value rather than its name.

If your goal is to change the time of an existing date, use the change method:

datetime.change(hour:21)
Sign up to request clarification or add additional context in comments.

5 Comments

OK. It parses the correct date now, but not 9pm! It still parses the datetime hour which is 9am.
Ah, that's right. You really don't need parse in this case. Can you use something like datetime.change(hour:17) instead?
Right!!! Funny I used the change method just 10 lines below this code but didn't think of it :D Would you edit your answer so that I accept it?
@fardin you may want to edit your question to clarify that you are using Rails.
@HélèneMartin you may want to edit your answer, too. DateTime.parse("#{datetime} 9pm") obviously doesn't work.
3

You can also try this

date = Date.new(2016,3,12)

DateTime.parse("#{date} 9pm")
## Output
Sat, 12 Mar 2016 21:00:00 +0000

OR

datetime = DateTime.new(2016,3,12,9)

DateTime.parse((datetime + 12.hours).to_s)
## Output
Sat, 12 Mar 2016 21:00:00 +0000

OR

DateTime.parse((datetime + 12.hours).to_s).strftime("%a, %d %b %Y %I:%M %p")
## Output
Sat, 12 Mar 2016 09:00 PM

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.