Ruby how to get 2018-08-25 from DateTime object? - ruby-on-rails

I have a DateTime property on one of my model objects.
Example data: "2018-08-28T01:00:00.000+00:00"
I am creating a new JSON object based of the DateTime property, but I just want to put this part into it 2018-08-28
I also want to grab the hour part and put it into the JSON object also. For example 01
Currently what I have is this JSON passed over.
{"date":"2018-08-25T18:00:00.000+00:00"}
I want this
{"date":"2018-08-25", "hour":"01"}

Parse the string into the valid DateTime instance and then print it back in any format you need with DateTime#strftime:
require 'datetime'
DateTime.
iso8601("2018-08-28T01:00:00.000+00:00").
strftime('%Y-%m-%d')
#⇒ "2018-08-28"
To get both a date and an hour one might do:
date, hour =
DateTime.
iso8601("2018-08-28T01:00:00.000+00:00").
strftime('%Y-%m-%d,%H').
split(',')
#⇒ ["2018-08-28", "01"]
To get a desired hash:
%w|date hour|.
zip(
DateTime.
iso8601("2018-08-28T01:00:00.000+00:00").
strftime('%Y-%m-%d,%H').
split(',')
).
to_h
#⇒ {
# "date" => "2018-08-28",
# "hour" => "01"
# }

Related

How to test specific dates that cannot be parsed

I need to test a specific array of dates to ensure that they are in the correct format, however I cannot use 'parse' because, if I do, the dates that are incorrect are sorted out. For instance, if I have an incorrect date with a month "13", it adds another year and sets the month to 1.
My code pulls in the dates from an SQL query:
table_birth_dates = self.class.connection.execute("SELECT birth_date FROM #{temp_table_name}").values.flatten
[
[0] "1980-30-54",
[1] "1980-30-54",
[2] "2020-09-10",
[3] "1890-10-30"
]
yr = 1900
year_test = table_birth_dates.select{|d| Date.parse(d).year < yr}
This now gives me an ArgumentError: invalid date.
I thought of using:
splitted_birth_date = table_birth_dates.first.split("-")
splitted_birth_date.first.to_i > 1900?
but if I try to loop through all of my dates, I'm not able to manipulate anything via splitting:
table_birth_dates.each do |birth_date|
birth_date.split("-")
end
What can I do with this?
I need to test a specific array of dates to ensure that they are in
the correct format...
If you get an error it means that the date is incorrect, you could rescue that error and do anything you want with that date to make it valid or whatever.
table_birth_dates.each do |birth_date|
begin
if Date.parse(d).year < yr
# do smth
end
rescue ArgumentError => e
# do smth with `d`
end
end
You could combine your select and split approaches together:
table_birth_dates.select { |d| d.split('-').first.to_i < 1900 }
#=> ["1890-10-30"]

append '01-' to strong parameter on rails controller

I have a form that uses jQuery datepicker for picking just the month and year.
$(".date-input").datepicker({
format: 'mm-yyyy',
startView: "months",
minViewMode: "months"
});
I have postgreSQL db on the backend with datetime column storing this date which apparently needs date in full format 'dd-mm-yyyy' to save it. While POSTing the form to my controller, this is what i came across:
Experience.update(date_from: '02-2016') updates the table with nil value for date_from column
So, the question is how can i append '01-' into this date_from param that i receive from POST request on the controller as Strong parameters.
Use the ISO8601 Date format (2016-10-21).
$(".date-input").datepicker({
format: 'yyyy-mm-dd',
startView: "months",
minViewMode: "months"
});
You can parse it with Date.iso8601(str) or DateTime.iso8601(str).
I would create a model level setter which handles this:
class Experience < ActiveRecord::Base # or ApplicationRecord
def date_from=(val)
super( val.is_a?(String) ? Date.iso8601(val) : val )
end
end
This means you don't have to worry about the params on the controller level. Just whitelist it like any other scalar value and let your model do the work.
I would just store the values as a DATE type (as the first day of the month). Thats gives you the maximum flexibility when comes to DB querying and also a sane format when you pull records so that you don't have to parse a string again.
This has nothing to do with strong parameters. When you get the data from the backend using strong params, you can access the information in the controller. You can try something like this -
def create
datestr = date_params[:datestr]
date = Date.strptime("01-".concat(datestr), "%d-%m-%Y")
Experience.update(date_from: date)
end
private
def date_params
params.require(:dateinfo).permit(:datestr)
end

comparing datetime and time produces a false result

I am using Mongoid and Chronic gem. Chronic produces a Time object, and Mongoid Date object produces a DateTime object. So in Mongoid, when i want to get today, I do something like this:
Lead.last.send('lead date') # => {DateTime}2015-03-30T00:00:00-04:00
In Chronic, when I parse today, I get this:
Chronic.parse('today') # => {Time}2015-03-30 23:00:00 -0400
And I compare the two with ==, it produces false, even though they are the same date. I need the following query to give a result, when 'lead date' refers to today:
Lead.where("lead date" => Chronic.parse('today'))
What options do I have?
Does this code accurately replicate your issue?
require 'chronic'
require 'date'
text = "2015-03-30T00:00:00-04:00"
datetime = DateTime.parse(text)
time = Chronic.parse(text)
datetime == time
#=> false
Use the DateTime #to_time method, or the Time #to_datetime method:
datetime.to_time == time
#=> true
datetime == time.to_datetime
#=> true

Date is not saving in correct format controller in RoR

my controller's action
time = Time.now.strftime("%d-%m-%Y")
# render text: time
u=SectionMst.new( :section_name => params[:section_name], :date_added => time , date_updated => time)
u.save
My modal code is
class SectionMst < ActiveRecord::Base
attr_accessible :date_added, :date_updated, :id, :section_name
end
render text:time is giving correct desired format but saving in %Y-%m-%d format
not able to get WHY??
The default db date format is: %Y-%m-%d %H:%M:%S. You can check this by executing Time::DATE_FORMATS[:db] in your rails console.
You can update this format by defining the format of your choice in an initializer file inside config/initializers/. Example:
# config/initializers/date_time_format.rb
Date::DATE_FORMATS[:db] = "%d-%m-%Y"
Time::DATE_FORMATS[:db] = "%d-%m-%Y %H:%M:%S"
This is the problem of your database, actualy DB support different format of dates, when you send date, after formatting it convert into own way so for avoid that use DB function to convert date. as date_format(date, format)
eg. SELECT ProductName, Price, FORMAT(Now(),'YYYY-MM-DD') AS PerDate
FROM Products
for making that sql query take an help from this link
Format used when converting and saving a date string to database with rails

Parsing a custom DATE_FORMAT with DateTime in Rails

How do I get DateTime to parse a custom date format(i.e. 'x-%Y')?
I've set the format within an initializer with (as per the RoR API):
Time::DATE_FORMATS[:x_year] = 'x-%Y'
Date::DATE_FORMATS[:x_year] = 'x-%Y'
and when I call:
DateTime.strptime('x-2011', 'x-%Y')
The correct result is returned, but
DateTime.parse('x-2011')
Throws an
ArgumentError: invalid date
never heard of such a possibility. However, you could still do something like:
class DateTime
class << self
alias orig_parse parse
end
def self.parse(string, format = nil)
return DateTime.orig_parse(string) unless format
DateTime.strptime(string, Date::DATE_FORMATS[format])
end
end
in your example it might look like that:
Date::DATE_FORMATS.merge!({:xform => "x-%Y"})
DateTime.parse('x-2011', :xform) #=> Sat, 01 Jan 2011 00:00:00 +0000
You could get rid of 'format' attribute and iterate && validate/rescue through DATE_FORMATS instead

Resources