我在要获取的输入数据中以字符串格式表示日期时间,如下所示。我需要将其转换为当地时间。我该怎么办?
日期时间字符串示例
str = "Aug 23 2018 03:49:17:017 PM IST"
答案 0 :(得分:2)
也许这可以使您步入正轨。 请参阅http://ruby-doc.org/stdlib-2.5.0//libdoc/date/rdoc/DateTime.html。
这是一个用法示例。
require 'date'
str = "Aug 23 2018 03:49:17:017 PM IST"
d = DateTime.strptime(str, '%b %d %Y %I:%M:%S:%L %p %z')
# Maybe you need %e - Day of the month, blank-padded ( 1..31) instead of %d - Day of the month, zero-padded (01..31)
p d.hour # => 15
p d.min # => 49
p d.sec # => 17
p d.second_fraction # => (17/1000)
p d.day # => 23
p d.month # => 8
p d.year # => 2018
p d.zone # => "+05:30"
# this way you can switch timezone
d = d.new_offset('utc')
p d.zone # => "+00:00"
p d.hour # => 10
d = d.new_offset('brt')
p d.hour # => 7
p d.zone # => "-03:00"
# to print back as string, use strftime:
p d.strftime('%Y-%m-%d %I:%M:%S %z') # => "2018-08-23 07:19:17 -0300"