I want to use HighCharts to render some historical data. The issue is the chart is working with dates which are parsed using Data.parse function. As explained here:
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
For example:
Date.parse("01/01/2013 08:00")
1357020000000
As I do not want to do JavaScript manipulation over the returned JSON I want to do the conversion in ruby. Is there such ruby function?
require 'date'
DateTime.parse("01/01/2013 08:00").strftime('%Q')
#=> "1357027200000"
Is this what you want?
For more Information see http://www.ruby-doc.org/stdlib-2.1.2/libdoc/date/rdoc/DateTime.html
I have managed to do this in the postresql like this search for EPOCH :
SELECT EXTRACT(EPOCH FROM my_date) as my_date
It gives me:
1410705430.59685
Then in the partial I just called to_i
Related
I've got date as string '2020-02-10 8,00' which I want to convert into Monday, 10th of February. I'm aware of this old topic however I cannot find (or use) any related information.
All I have is just parsed string to date - Date.parse '2020-02-10 8,00'
You are halfway there! Date.parse '2020-02-10 8,00' produces a ruby Date object, as you have noted. You now have to apply strftime. However strftime doesn't have any ordinalization so that piece has to be done manually.
date = Date.parse('2020-02-10 8,00')
date.strftime("%A, #{date.day.ordinalize} of %B") #=> Monday, 10th of February
the ordinalize method is provided by ActiveSupport.
If this format will be used multiple times in your app, you may wish to add an app-wide format:
# in config/initializers/time_formats.rb
Date::DATE_FORMATS(:ordinalized_day) = lambda{|date| date.strftime("%A, #{date.day.ordinalize} of %B")}
# anywhere in the app
Date.today.to_formatted_s(:ordinalized_day)
I need to use strptime to convert a timestamp string with milliseconds to a Time object.
A work around is using parse:
t= Time.parse('29 Sep 2013 12:25:00.367')
=> 2013-09-29 12:25:00 -0400
But it is very important for my code to use strptime, because I want to be able to pass multiple types of format including: "HH:MM", "HH", etc. through the function.
I can do it with nanoseconds like this:
Time.strptime("12:34:56:789434", "%H:%M:%S:%N")
=> 2016-03-16 12:34:56 +0100
I want something like this:
Time.strptime("12:34:56:789", "%H:%M:%S:%[insert magic letter that represent milliseconds]")
My thought is that there must be a way to do it with milliseconds as well.
Is it possible and how?
Try %L.
Refer to Ruby's DateTime documentation.
If you can update to Ruby 1.9.3, it supports this using %3N:
http://ruby-doc.org/core-1.9.3/Time.html#method-i-strftime
I need to convert a string that represents a date to a timestamp object in Ruby.
For example:
date_string = "18-Feb-2016 09:01:04"
convert to a timestamp like so
2016-02-18 14:01:04
I need to save this to a mysql database were the column is type timestamp.
I have researched this for most of the day and can not find a solution. I know you can use Time.parse but that includes timezone and DateTime.parse().to_time includes the timezone. Since it has to be a timestamp i can not use strftime method.
I need the time to be included because it will be used for calculation purposes.
Any help would be greatly appreciated.
Thank you
TL;DR
datetime = DateTime.parse("18-Feb-2016 09:01:04").to_s(:db)
returns
"2016-02-18 09:01:04"
Here's a quick explanation...
1. Convert your string to a Date object with DateTime.parse
You can use the .parse method from the Date or DateTime class in order to parse a string. The parse method will return a Date object like this:
$ DateTime.parse("18-Feb-2016 09:01:04")
$ => #<DateTime: 2016-02-18T09:01:04+00:00 ((2457437j,32464s,0n),+0s,2299161j)>
.parse is a method provided by Ruby.
2. Format the string with DateTime.parse.to_s
Ruby on Rails gives you access to the DateTime.to_formatted_s method to change the formatting of the Date object prior to storing it in your database.
To match the format that you specified:
$ datetime = DateTime.parse("18-Feb-2016 09:01:04").to_formatted_s
Note: to_s is aliased from to_formatted_s and to_formatted_s is a method provided by Rails, not Ruby.
Use to_datetime method in Rails.
"12-10-2015".to_datetime
=> Mon, 12 Oct 2015 10:36:00 +0000
http://apidock.com/rails/String/to_datetime
Edited to add precise answer.
You can use .to_time or .to_datetime, the .to_time returns the date and time with timezone but the .to_datetime returns full date with week name but it shows +0000 as timezone, you will see the difference in both the formats, see the following example.
# used .to_time
"18-Feb-2016 09:01:04".to_time
## Output
2016-02-18 09:01:04 +0530
# used .to_datetime
"18-Feb-2016 09:01:04".to_datetime
## Output
Thu, 18 Feb 2016 09:01:04 +0000
I've interpreted the question to be that you wish to convert the string "18-Feb-2016 09:01:04" to the string "2016-02-18 14:01:04" (generalized to arbitrary date-time strings, of course).
Let:
str = "18-Feb-2016 09:01:04"
What you want is done in two steps. The first is to convert this string to a DateTime object, that is, an instance of the class DateTime. The second step is to construct the desired string from the DateTime object.
One way to create the DateTime object is to use the method DateTime::parse:
require 'date'
DateTime.parse(str)
#=> #<DateTime: 2016-02-18T09:01:04+00:00 ((2457437j,32464s,0n),+0s,2299161j)>
That works fine for the string format you gave, but can be problematic with other formats. For example:
DateTime.parse "4-5-16 09:01:04"
#=> #<DateTime: 2004-05-16T09:01:04+00:00 ((2453142j,32464s,0n),+0s,2299161j)>
As long as you know the format that will be used, it's generally better to use DateTime#strptime with the appropriate pattern comprised of format directives:
pattern = "%d-%m-%y %H:%M:%S"
DateTime.strptime("4-5-16 09:01:04", pattern)
#=> #<DateTime: 2016-05-04T09:01:04+00:00((2457513j,32464s,0n),+0s,2299161j)>
See DateTime#strftime for the format directives.
For the problem at hand:
dt = DateTime.strptime(str, "%d-%b-%Y %H:%M:%S")
#=> #<DateTime: 2016-02-18T09:01:04+00:00 ((2457437j,32464s,0n),+0s,2299161j)>
The second step is to construct the desired string with the above-referenced strftime method:
dt.strftime("%Y-%m-%d %H:%M:%S")
#=> "2016-02-18 09:01:04"
I'd like to mimic the functionality of the Mac calendar quick event or Fantastical's quick entry. Using the Chronic gem, I can pass a string like:
"Today at 3pm"
=> 2014-01-24 15:00:00 -0600
Chronic parsing doesn't work if you pass in something like:
"Eat at Joes Today at 3pm"
=> nil
What I've done so far is use a simple regex to split a string at a word normally used to return a date with Chronic. The initial regex is simple:
scan(/(.+)(tomorrow{1}.+|in\s.+|next\s.+|today\s.+)/)
This returns an array with the "title", if you will, and the string I want to sent to Chronic to parse for me.
Two questions:
Is this really the best way to do this? I'd have to provide some mega regex to split whatever string I think my users will submit here.
Would hacking at Chronic be better? It's already parsing the dates for me, but my initial thought is no because if you pass Eat at Joes Today at 3pm to Chronic.parse, it'll return nil. It seems it doesn't recognize the part of the string for formatting the date in it's present form.
I wouldn't edit Chronic. Chronic's only function is to parse natural language date time, not other input. You might be interested in the Nickel gem here:
https://github.com/iainbeeston/nickel
This separates time from other language.
n = Nickel.parse("use the force on july 1st at 9am", Time.now)
n.message #=> "use the force"
n.occurrences.first.start_date #=> "20110701"
I am importing data from CSV inside Rails 3.2 and saving it to mongodb collection and everything works fine except the date field. The imported date format is DD/MM/YYY. Please how can I convert the imported date to YYYY-MM-DD?
Thanks
You could use date parsing like this:
Date.strptime('01/02/2003', '%d/%m/%Y').to_s #=> "2003-02-01"
Date.strptime creates a Date object from a string in the given format
Date#to_s returns it in the ISO 8601 format (i.e. YYYY-MM-DD)
But it depends on how big your CSV is - this would create a bunch of intermediate Date objects which would be a bit slower than a (slightly ugly) string indexing approach:
def reformat_date(date)
"#{date[6..9]}-#{date[3..4]}-#{date[0..1]}"
end
reformat_date('01/02/2003') #=> "2003-02-01"
Update
I was curious so I ran some quick benchmarks - the date parsing method was about 2.7 times slower than the string method (5.289s vs 1.981s for a million conversions, Ruby 1.9.3/Windows). YMMV.
You may need
require 'date'
Then use the following statement to parse the date:
d = Date.strptime('09/10/2012', '%d/%m/%Y')
Using the following examples will return the right format:
d.year #=> 2012
d.mon #=> 10
d.day #=> 9
d.strftime('%Y/%m/%d') #=> "2012/10/09"
Then save it to the database. I'm not familiar with mongodb, though, but I'm sure you know what to do.
For more information on date parsing you should visit http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html.