Ruby strptime %Y returning wrong date/year - ruby

I have a method that returns date in the format I want to have it. I work with calendar weeks, so I don't save them as dates and convert them in the method to display them nicely in the view (when necessary).
Anyway, this is the method:
def formatted_date(year, week, day)
Date.strptime("#{year}-#{week}-#{day}", '%Y-%V-%u')
end
When type in formatted_date(2022, 47, 21) it returns the date for today, but when I type in formatted_date(2023, 47, 21) it also returns the day for today, not for 2023.
Why is that? And how do i do it correctly? I thought it just returns the year with four digits which is the case here, right?

You are passing the wrong format to strptime which is why the year isn't changing. Do something like this:
def formatted_date(date)
DateTime.strptime(date, "%d-%m-%Y").strftime("%Y-%m-%W")
end
Pass the date format like this formatted_date("21-02-2022") and you will get the result in the format you are looking for. Obviously, you can change strftime("%Y-%m-%W") the way you want to.

Related

Ruby Date Gem Invalid Date

So I am iterating through a hash where one of the key/values is {date: => 'MM/DD/YYYY'}
When I iterate through, I am using the date gem to find out what day of the week that each date is, (0-6).
To get a day of the week for the index I am currently at as an integer so i can compare it to another integer, the idea is to check if the day of the week of the index is the same as the day of the week i am searching for.
To get that int I run the following commands:
d = Date.parse(hash[i].values[2])
day_of_the_week = d.cwday
When i do this on its own for just a cherry-picked date this works fine, but I am iterating through the hash, what i get is:
search.rb:25:in `parse': invalid date (ArgumentError)
for the particular date '9/13/17'.
Is there something wrong with '9/13/17'? Why does this actually work for other days (it starts at '9/5/17') and then get randomly stuck at this day?
And as I was writing this, I did a little digging and found exactly what index it was:
d = Date.parse(hash[4224].values[2])
day_of_the_week = d.cwday
Gives me the same error, I am completely baffled, what is going on? Also its not the lack of MM in 9/etc because every other month is the same way.
EDIT: The result should be 2, September 12th 2017 was a Tuesday.
You need to pass the format of your date, use
Date.strptime('9/13/2017', '%m/%e/%Y').
I found that using:
d = Date.strptime(hash[i].values[2], '%m/%d/%Y')
Does creates a date object of the current index better than:
d = Date.parse(hash[i].values[2].to_s)
Replacing that did the trick.

Find objects that match today's date in Ruby

I have a calendar object that lists a number of object events. Each event contains a start_date. So when I call
event.start_date it gives me "8/6/2017 3:00pm"
I want to be able to find all the events with today's date. I'm using Chronic. So
Chronic.parse('today') would give me "8/6/2017 00:00:00" or something like it
I'm not using Rails just Ruby. Thus, I don't have all the special methods that come with Rails to help me with this.
If I enter a specific date I could find the events with that specific date by using
event.start_date.starts_with?("8/6/2017")
but I haven't figured out how to do it with today's date.
Any help would be appreciated.
time = Chronic.parse('today')
target_date = Chronic.parse('8/6/2017').to_date
puts time.to_date == target_date
Time class (what Chronic returns) holds datetimes. Date only holds dates. If you convert Time to Date, you discard the time-of-day information, and then you can compare just the date itself.
Note that Date.today is the same thing as Chronic.parse('today').to_date (and same as Time.now.to_date). Also note that Time class doesn't have #to_date unless you require 'time', but Chronic does it for you.

Parse hours from string with space delimiter

I have file strings that contain dates in their heading, stuff such as 2017-03-06 092328 - iPhone - Music Show - street performance, while walking the dog.m4a
I would like to parse the date our of this string, because I need to print it in a podcast friendly format.
I'm able to parse out the date, but for some reason the time component refuses to be parsed out :)
Date.strptime("2017-03-06 092328", "%Y-%m-%d %H%M%S").strftime(%Y-%m-%d %H%M%S)
Expected output:
"2017-03-06 092328"
Actual output
"2017-03-06 000000"
Your problem is that Date is (what a surprise!) a date, as in, "Not a time, just a date".
require 'time'
Time.strptime("2017-03-06 092328", "%Y-%m-%d %H%M%S").strftime("%Y-%m-%d %H:%M:%S")
#=> "2017-03-06 09:23:28"
To be fair :
the documentation of Time#strptime mentions that it's based on Date#strptime
Date._parse("2017-03-06 09:23:28") will happily return {:hour=>9, :min=>23, :sec=>28, :year=>2017, :mon=>3, :mday=>6}
If you find it confusing that a Time object has a date and a time but that Date just has a date, you could use DateTime.

How to get date time from DB date in Ruby

I need to get time and date from database date like "2015-08-27T12:09:36Z". I tried but not get any solutions where I get date and time in different variable.
I need to get it in Ruby. No rails in my application.
I used below code but not getting.
Time.strptime("2015-08-27T12:09:36Z", "%Y-%m-%dT%H:%M:%S%z").in_time_zone
Any one have a experience in it?
Thanks
I don't have enough reputations to comment so am posting comment as answer, are you looking for this
Time.now.strftime('%Y-%m-%dT%H:%M:%SZ')
Which will give the pattern you asked for. Z represent the time zone if you use
%z - Time zone as hour and minute offset from UTC (e.g. +0900)
%:z - hour and minute offset from UTC with a colon (e.g. +09:00)
%::z - hour, minute and second offset from UTC (e.g. +09:00:00)
%Z - Time zone abbreviation name
Check for more
http://apidock.com/ruby/Time/strftime
My Updated answer after your comment
require 'date'
DateTime.parse("2015-08-27T12:09:36Z").strftime('%Y-%m-%dT%H:%M:%SZ')
In your code change Time.strptime('') to DateTime.strptime('')
First, you need to require 'date'. Ruby has built-in Date and Time classes without that require, but the library provides more functionality.
If you have a string retrieved from the database in ISO-8601 format, and you want to turn it into a date and time, just use DateTime.iso8601(string) to get a DateTime object. You can extract the date and time components however you like after that.
irb(main):001:0> require 'date' #=> true
irb(main):002:0> dt = DateTime.iso8601("2015-08-27T12:09:36Z") # DateTime object
irb(main):003:0> d = dt.to_date # Date object
irb(main):004:0> t = dt.to_time # Time object

Any reason to use Date?

There are at least three types which represent time: Time, Date and DateTime(from ActiveSupport).
My problem is, could DateTime totally replace Date? In other words, if I can use DateTime, is there any reason to use Date instead?
require 'date'
d = Date.today
dt = DateTime.now
p Date.public_methods - DateTime.public_methods
#=>[:today]
p DateTime.public_methods - Date.public_methods
#=>[:now]
p d.public_methods - dt.public_methods
#=>[]
p dt.public_methods - d.public_methods
#=>[:hour, :min, :minute, :sec, :second, :sec_fraction, :second_fraction, :offset, :zone, :new_offset]
DateTime is a subclass of Date. Using DateTime, you lose the today Class method and get now in return. You don't lose instance methods.
If you want to store only the date, for example a birthday, or a certain day where an event takes place, then it can be easier to use only date. Then you have no troubles which arise from different time zones and time zone calculations. If you use DateTime, then if you add an offset of -2 hours to 00:00 am, you get 10:00 pm of the previous day.
Date does not store any information about the time, neither with the timezone. So you might get into trouble if at some point you'll need to use time data.
Cf this link, which I found clear about what classes should be used, when, and how.

Resources