How can i remove the milliseconds from date time in rails? - ruby-on-rails

I have to compare the date in rails to get the values after that date I have send the date as "2013-03-04T06:26:25Z"but actually the record in the db contains date as follows 2013-03-04 06:26:25.817149 so when i check with the date it also returns that record but i want records after that date. how can i remove the milliseconds from the db? please help me.

I had a similar problem
Update your time object like this before sending it to the database :
time.change(:usec => 0)

Since ruby 1.9 you can use round
t = Time.now.round
t.usec # => 0

I was also having this problem, however when I was applying the change as indicated in #Intrepidd's answer, it wasn't affecting the microseconds of my time object.
Please note that (at least currently) the :usec key only works with the Time#change method, and not with the DateTime#change method.
The DateTime#change method ignores the keys that it doesn't accept, so you wouldn't be able to tell that your attempted change of the microseconds didn't work unless you inspected the object further (such as with DateTime#rfc3339(9)).
So before you attempt this change, make sure that you are working with a Time object, not a DateTime object.

Related

Rails: How to manage a "static" time-value attribute?

What is the best way with Rails to have a “time” attribute (selected by the user) which is supposed to always be displayed as the same “static” time value?
(Meaning: It should always show the same time, for example “14:00”, completely independently of any user’s time zone and/or DST value.)
Until now, I have tried the following setup:
In the MySQL database, I use a field of the type time (i.e. with the format: 14:00:00)
In the Rails view, I use the helper time_select (because it’s really handy)
However, it seams that with this approach, Rails’ ActiveRecord will treat this time value as a full-blown Ruby Time object, and therefor convert the value (14:00:00) to the default time zone (usually set to ‘UTC’) for storage and then convert it back to the user’s time zone, for the view. And if I’m not mistaken, this also means that the fluctuating DST value will make the displayed time value fluctuate throughout the year (and the same happens if the user moves to another time zone).
So what is the best way to manage a simple “static” time attribute with Rails?
If you don't want any time related functionality, why not save it as an string field. Since from your question description its evident that functionalities such as timezone doesn't effect your use case, so just make it a normal VARCHAR(8) and save the value as a string and parse it such as Time.now.strftime("%H:%M:%S") before saving it to the database, you can also write this logic inside your ActiveRecrd model class
def static_time=(value)
super(value.strftime("%H:%M:%S"))
end
you can somewhere in the code say model_object.static_time=Time.now and this will automatically parse it, if you want to get the time as a ruby object retaining the format you can simply do it defining a custom getter.
def static_time
current_time = Time.now
time_keys = [:hour, :min, :sec]
current_time.change(**Hash[time_keys.zip(super.split(":"))])
end

Date conversion is not working as expected, time always remains after conversion

I'm trying to do the most simple of things, convert a date to a different date format but I can't seem to do it as my knowledge in ruby is practically zero.
I tried to read through this and tried all of the possible .to_formatted_s() versions but none of them works. The time seems to always remain there no matter what. Since this date doesn't come from a date.new() but rather an existing object property I'm guessing this is the reason why .to_formatted_s() isn't working as in the example in the docs. I could be horribly wrong though.
How do I convert this date format:
2015-07-01 01:59:59 +0200
To this:
2015-07-01
My attempts were:
// inv.end is "2015-07-01 01:59:59 +0200"
inv.end.to_formatted_s(:db)
inv.end.to_s(:db)
inv.end.to_formatted_s(:iso8601)
Which all outputted 2015-06-30 23:59:59.
What am I doing wrong?
require 'date'
DateTime.parse("2015-07-01 01:59:59 +0200").strftime('%Y-%m-%d')
http://apidock.com/ruby/DateTime/strftime
The above answer is correct.If you want to perform the same date format repetitively , then create a file in initializers & write the below code:
class ActiveSupport::TimeWithZone
def my_format(options = {})
strftime('%m-%d-%Y')
end
end
& after the datetime object just write my_format like #user.updated_at.my_format

Rails initialize variables in server startup

I want to initialize a variable in rails and use it in a controller's action, but the variable should have a fixed value when the server starts. I have tried defining it inside a controller's action and it get's the same initialized value for every request. For example, i want to initialize a date.now and have the same date after 15 days also.
Update
I am implementing a coming soon page in which a timer is shown 15 days from now. If i implement it in a action inside a controller, it shows new date every time the action is invoked.
Please Help
If you want to create a CONSTANT in rails then you can simply put it into the initializer file. For eg, create a file name constants.rb inside initializer:
#config/initializers/constants.rb
TEST_VALUE = 10
And to access this CONSTANT from your controller, just call for TEST_VALUE. for eg,
#controllers_path/some_controller.rb
.....
def some_def
#value = TEST_VALUE # this will be enough to fetch the constants.
end
But, make sure you restart your server after changing the intializer.
You're looking to create a constant, which is basically a variable which doesn't change its value
You'd typically set these with initializers:
#config/initializers/your_initializer.rb
YOUR_CONSTANT = your_date
To maintain a persistent date, you'll have to give some more context on what you're using it for. It will be difficult to create this each time Rails loads (how to know which Time.now to use), so giving us more info will be a good help
You can also use an opposite approach. Assuming you should know the date when the new feature comes (for example 2014-04-04 18:00) you can just find a number of seconds left till the target date:
#seconds_left = Time.parse('2014-04-04 18:00').to_i - Time.now.to_i
then pass it to client side and implement a timer. So you'll just need to store a string representation of a target date.
Obvious disadvantage of this approach is that you should adjust that target time each time you want to introduce a new feature.

ruby soap datatime adds Z at the end

I have some strange behavior with ruby.
In a rake file I pass in a date to soap method. In the response it appends a Z at the end of the date.
in a lib file, same thing, same requirements, it doesn't.
I need the case where it doesn't. It executes the same.
What could it be?
<n1:startDate>2009-08-18T00:00:00-05:00Z</n1:startDate>
<n1:endDate>2009-08-26T00:00:00-05:00Z</n1:endDate>
The letter at the end is an indicator of the timezone (in this case UTC). The timestamp is in ISO8601 format (pretty much the standard now-a-days for all things internet), so I'm not sure why you'd want otherwise.
Without seeing the code that's generating it I'm not sure what more I can offer. Why do you want it without the 'Z'?
You've got an ISO 8601 formatted date there, the Z indicates 'Zulu' time or UTC, but not sure why you're getting differing formats though.
I am accessing an API which doesn t support this ISO standard. The date should not have a Z at the end. but when the soap response is build, it adds it. And I don t send it with that Z .. as I pass it to the web method.
Here is the code
factory = SOAP::WSDLDriverFactory.new(WSDL_STATS)
driver = factory.create_rpc_driver
driver.wiredump_dev = STDOUT
response = driver.getAllLeads({"pubID" => AFF_ID_TEST, "startDate" => start_date, "endDate" => end_date})
The end date that are passed, tried various .. isn t with that Z , from zone, at the end.
If I overwritte the zone method, maybe it will work, but I don t want to do that.
<n1:startDate>2009-08-18T00:00:00-05:00Z</n1:startDate>
<n1:endDate>2009-08-26T00:00:00-05:00Z</n1:endDate>
I pass the date without the Z, but when the soap is constructed the Z is added somehow.
This is what I want
<n1:startDate>2009-08-18T00:00:00-05:00</n1:startDate>
<n1:endDate>2009-08-26T00:00:00-05:00</n1:endDate>
Thank you ;)

How do I work with Time in Rails?

I've been pulling my hair out trying to work with Time in Rails. Basically I need to set all time output (core as well as ActiveSupport) to the server's local time -- no GMT, no UTC, etc. I've seen various posts relating to Time, but they usually involve someone's need to set it for each user. Mine isn't nearly as complex, I simply want consistency when I use any Time object. (I'd also appreciate not receiving errors every 3 seconds telling me that I can't convert a Fixnum (or some other type) to string -- it's Ruby, just do it!)
I also seem to be getting drastically different times for Time.new vs the ActiveSupport 1.second.ago. Anyway, does anyone have any quality suggestions as regards working with Time in Rails?
If you just want Time objects to be consistent, then why not stick with UTC? I just tried Time.new and 1.second.ago using script/console and I get the same output (give or take a second for typing the command). How are you doing it?
Somewhere in your initializers, define the format(s) that you want to use.
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:default => '%m/%d/%Y %H:%M')
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:my_special_format => '%H:%M %p')
Then when you want to print a Time object, it works like the following example. Notice that the Time object in my console is already aware of my time zone. I'm not performing any magical transformations here.
>> t = Time.now
=> Wed Jul 15 18:47:33 -0500 2009
>> t.to_s
=> "07/15/2009 18:47"
>> t.to_s(:my_special_format)
=> "18:47 PM"
Calling Time#to_s uses the :default format, or you can pass in the name of the format you'd rather use like I did with :my_special_format.
You can see the various options for formatting a Time object here.
If u don't want to store each user time setting, the only solution is to use javascript time system because it work on user client time. For example i have an application that each time user try it, the app will create some example data with each data have a initial date value "today". At first time, it confuse me a lot because my host server is in australia and lot of user is on western part, so sometime the initial date value is not "today", it said "yesterday" because of different time region.
After a couple day of headache i finally take decision to JUST use javascript time system and include it in the link, so when user click the "try now" link it will also include today date value.
<% javascript_tag do -%>
var today = new Date();
$("trynow").href = "<%= new_invitation_path %>?today=" + today.toLocaleString();
<% end -%>
Add the following to config/environment.rb to handle time correctly and consistently all the time within the context of Rails. It's important to know that it will store your times to the database in UTC -- but this is what you want -- all the conversion is done automatically.
config.time_zone = 'Pacific Time (US & Canada)'
You can run rake time:zones:local from your Rails root directory to get a list of valid time zone strings in your area.
A quick addition to the DATE_FORMAT solution posted above. Your format can be a string, in which case it works as noted above by calling strftime, but you can also define the format as a lambda:
CoreExtensions::Time::Conversions::DATE_FORMATS.merge! :my_complex_format => lambda {|time|
# your code goes here
}

Resources