简体   繁体   中英

Split string and put in variables with ruby

I got the following input from user 'Wed, 02 Nov 2016 19:00:00'. How can I split this string for date and time and place in variables with ruby? How can I get the same string from the variables then?

I look throw regexp and date docs on ruby.tried to write smth:

require 'date'

puts DateTime.strftime('Wed, 02 Nov 2016 19:00:00', '%a, %d %b %y %H:%M:%S')

got the error

test-2.rb:17:in `<main>': undefined method `strftime' for DateTime:Class (NoMethodError)
Did you mean?  strptime
               _strptime 
 irb(main):001:0> require 'time'
=> true
irb(main):002:0> dt = DateTime.parse('Wed, 02 Nov 2016 19:00:00')
=> #<DateTime: 2016-11-02T19:00:00+00:00 ((2457695j,68400s,0n),+0s,2299161j)>
irb(main):003:0> dt_date = dt.strftime('%Y/%m/%d')
=> "2016/11/02"
irb(main):004:0> dt_time = dt.strftime('%H:%M:%S')
=> "19:00:00"
irb(main):005:0>
require 'time'

time = Time.parse("Wed, 02 Nov 2016 19:00:00")

p time #2016-11-02 19:00:00 +0000  
p time.day #2
p time.month #11
p time.year #2016

You can parse the time like so by requiring the module time. It will take the string date provided by the user, and convert it to an actual date and time recognized by ruby. Then you can use the built in methods provided by the time module and store that data in to variables. I hope that answers your question.

Parse a time object

This code extracts a Time object and converts it back to a date, time and date_time string.

require 'time'

time = Time.parse("Wed, 02 Nov 2016 19:00:00")

date_str     = time.strftime('%a, %d %b %Y')    #=> "Wed, 02 Nov 2016"
time_str     = time.strftime('%T')              #=> "19:00:00"
datetime_str = time.strftime('%a, %d %b %Y %T') #=> "Wed, 02 Nov 2016 19:00:00"

Split the string directly

If you don't need a Time object, you can just split the string around the last space :

date, time = "Wed, 02 Nov 2016 19:00:00".split(/ (?=\S+$)/)
date # => "Wed, 02 Nov 2016"
time # => "19:00:00"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM