简体   繁体   English

分割字符串并用ruby放入变量

[英]Split string and put in variables with ruby

I got the following input from user 'Wed, 02 Nov 2016 19:00:00'. 我从用户“ Wed,02 Nov 2016 19:00:00”获得了以下输入。 How can I split this string for date and time and place in variables with ruby? 如何使用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: 我看起来在ruby.tried上扔正则表达式和日期文档试图写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. 它将采用用户提供的字符串日期,并将其转换为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. 此代码提取一个Time对象,并将其转换回日期,时间和date_time字符串。

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 : 如果不需要Time对象,则可以将字符串拆分为最后一个空格:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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