Proper way to parse and format a DateTime object? - ruby-on-rails

In rails I have DateTime object as:
2014-08-21 18:14:12 UTC
I want to display it as:
08-21-2014
I can hack this as follows:
"2014-08-21 18:14:12 UTC".to_s.sub(/(\d*)(-)(\d*-\d*)/, '\3\2\1').first(10)
But I prefer the proper Rails/ Ruby way and not having to convert the Date object to a string. Thanks!

See DateTime#strftime:
> DateTime.now.strftime '%m-%d-%Y'
=> "08-22-2014"
And please, please, please don’t use that format, unless you have no choice. Hyphens should only be used for the Y-m-d format. Use slashes or dots if possible. (Even better, use Y-m-d!)

Just use strftime to get various formats of date & time.
> DateTime.now.strftime("%m-%d-%Y")
=> "08-23-2014"
Read more about strftime

Related

How to get the date Format directives of a date string

I have a string in date format. It would be "2020-09-30", "09-30-2020", etc.
I would like to get back the Format directives of the date string.
For example, if the string is "2020-09-30", I would like to get back "%Y-%m-%d".
Check the below link by tweaking some the methods a bit you can get the desired result
https://railsexamples.com/ruby-date-formatting/

Rails [AXLSX]: Change Currency

I need to change the currency format on an Excel file that is exported.
The default currency pattern is US (1,000.00) [One Thousand] and I need it to become PT-BR format (1.000,00) [One Thousand].
I have tried implementing this way:
formated = workbook.styles.add_style(format_code: '$#.##0,00')
but the only thing it did, was add more zeroes after the .
How should I do it?
Welcome to SO :)
Yo might try this:
formated = workbook.styles.add_style(:format_code => '#.###,##')

extract information from particular string

I am new to ruby on rails. I have passed parameters ISDCode,AreaCode and Telephone number using POST from a form.
I have a string with information of the format countryName(ISDCode) passed in the variable ISDCode. For example "United States of America(+1)".
Now I want to save only the value of the ISDCode in the database.
What would be the ideal way to extract the ISD Code from the string?
Should I extract the ISD Code in Javascript before user POSTs the form or should I extract it in the model using a callback ?
Also is regex the only way to extract the information?
Since the string is from auto completion, the ISDcodes should be existing in your database. So the best solution may be including an extra parameter (with a hidden input), like isdcode_id, then you simply use isdcode_id in your model. This way you can avoid the trouble to parse the string.
If this is not feasible, regex could be the best way to extract the information. You can override the setter in the model to do it.
use regular expression to match ISDcode
"United States of America(+1)" =~ /(\+[\d]+)/
puts $1
If you are interested in getting just the ISD Code alone, this should work:
"United States of America(+1)".gsub!(/[^\+\d]/, "")
NB: You can have this in your view helper and just call the helper on the string before persistence
Already answered, but I'd like to offer an alternative to getting the ISD Code:
isd = "United States(+1)"
puts isd[/[+]*[\d]{1,4}/] # +1
This regexp matches:
0001
+1
+01
etc.
I prefer to use js to extract information in the client side and make a validation in the model. By this way, you can get what you want and make sure it's correct.

How to format a date to JSON in Rails?

I need to produce a date in Rails which looks like this:
/Date(1294268400000)/
I have tried various combinations of DateTime, to_i, to_json but never managed to get the /Date()/ thing.
Do I have to simply get my date in ms and then wrap the /Date(and )/ manually, or is there a built in method?
What about (ruby 1.9.x)?:
Time.now.strftime("/Date(%s%L)/")
=> "/Date(1335280866211)/"
You should try
new Date(posixMillisecondsHere)
first. MDN says that calling the Date function outside of the constructor context (i.e., without the new) will always return a string containing a formatted date rather than a Date object.
Strictly speaking, when you do that, you are writing JavaScript and not JSON. JSON cannot contain Date objects.
RFC 4627 says
2.1. Values
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:
false null true
If you want to put a Date into what is strictly considered JSON and then get it back out, you must choose some way of using the JSON primitives (to wit, objects, arrays, numbers, strings, etc.) to encode a Date.
If you want to get a Date back out of JSON, whatever parses your JSON must understand the convention that you used to encode the Date.
Hope these are credible and/or official enough to help.
What about something like this:
in your config/en.yml file:
en:
time:
formats:
json: "/Date(%s%L)/"
and than in the view:
<%= l(Time.now, :format => :json) %>
Please note that you would need access to the helpers in the method that renders json. So it won't work if you are using ActiveRecord#to_json method for generating jsons.
Check out this question:
c# serialized JSON date to ruby
... simple answer seems to be to create a parse_date method.
It's the UNIX Epoch (seconds since 1970-01-01) right? What about using DateTime#strftime method?
# Taken from the Ruby documentation
seconds_since_1970 = your_date.strftime("%s")
UPDATE: OK, it's milliseconds, according to the documentation you can use your_date.strftime("%Q") to get the ms (but I've not tried yet).

Is there an equivalent in RoR for PHP's gmdate?

For instance, if I called:
gmdate("M-D-yTh:i:s")
Is there something similar for this case in RoR? I guess I could always DateTime.now.hour, DateTime.now.year, etc. etc. but that seems extremely wrong.
See strftime() in Ruby's documentation on Time, which formats a time according to the directives in the given format string.

Resources