0

I want to convert 2 dates

"05/14/2020" to 05-14-2020 00:00:00. (start of the day)

"05/31/2020" to 05-31-2020 23:59:59. (end of the day)

1
  • What is the code you are having trouble with? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? Please, provide a minimal reproducible example. Please be aware that Stack Overflow is not a code-writing service, you need to show your efforts! Commented May 15, 2020 at 8:37

2 Answers 2

1

I would do this:

Date.strptime("05/14/2020", "%m/%d/%Y").beginning_of_day
#=> Thu, 14 May 2020 00:00:00 UTC +00:00

Date.strptime("05/31/2020", "%m/%d/%Y").end_of_day
#=> Sun, 31 May 2020 23:59:59 UTC +00:00
Sign up to request clarification or add additional context in comments.

6 Comments

I am getting error for both. NoMethodError (undefined method `beginning_of_day' for #<Date: 2020-05-14 ((2458984j,0s,0n),+0s,2299161j)>)
Use DateTime.strptime instead of Date
@Mahant Date#beginning_of_day is a Rails method (your question has the ruby-on-rails tag)
@Stefan I did not see any rails tag individually
@Mahant tags categorize questions. Your question has two tags: ruby-on-rails and ruby. Therefore, we assume that your question is about Ruby on Rails. If your question isn't related to Rails, you should remove that tag (there's an edit button).
|
0

You can use Time.strptime to parse a string that's composed of your date string and a fixed time value:

require 'time'

from = '05/14/2020'
to = '05/31/2020'

Time.strptime("#{from} 00:00:00", '%m/%d/%Y %H:%M:%S')
#=> 2020-05-14 00:00:00 +0200

Time.strptime("#{to} 23:59:59", '%m/%d/%Y %H:%M:%S')
#=> 2020-05-31 23:59:59 +0200

2 Comments

HI Stefan, Your slice_before suggestion to my question perfectly worked for me. Since my question got downvoted, I deleted it. Thanks your solution resolved my problem. I will delete this comment once after you have seen it.
@Rajagopalan you're welcome. But don't delete questions just because you got a downvote. People spent time reading it and providing help (via comments and answers). Deleting the question invalidates their efforts.

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.