Reputation: 944
I am attempting to change an SQL datetime variable (2016-06-09 14:29:34
) into a format that looks like this (00:00_20160601
). I have tried to follow a couple of SO questions that will allow me to format a Time object.
This is what I have done so far:
start_datetime = "2016-06-09 14:29:34"
t =Time.new(start_datetime)
t.strftime("%H:%M_%Y%d%m")
This results in the time being formatted to 2016-01-01 00:00:00 +0000
, which is obviously not what I want. I was wondering if someone could help me format the datetime object the way I specified?
Upvotes: 0
Views: 364
Reputation: 211740
You can do this with DateTime
:
require 'datetime'
DateTime.parse("2016-06-09 14:29:34").strftime("%H:%M_%Y%d%m")
#=> "14:29_20160906"
The format you're feeding in is basically ISO-8601 so it's parsed by default.
Feeding that value into Time.new
is completely incorrect. The first argument there is the year, the rest have to be supplied separately. That's why you get 2016-01-01
, since everything else comes out as defaults.
Time.new
is converting automatically and the result of "2016-06-09 14:29:34".to_i
is 2016
.
Upvotes: 2
Reputation: 160621
It's not entirely clear why your day value changes from 09
in the input to 01
in the desired output, so I'll use the normal thing and output the same as was input:
require 'time'
start_datetime = "2016-06-09 14:29:34"
t = Time.strptime(start_datetime, '%Y-%m-%d %H:%M:%S')
t.strftime('00:00_%Y%m%d') # => "00:00_20160609"
Since the hours and minutes are being thrown away there are a couple of other ways to go about this.
Ignore the hours and minutes when parsing:
t = Time.strptime(start_datetime, '%Y-%m-%d')
Or use a Date object instead of a Time object:
require 'date'
start_datetime = "2016-06-09 14:29:34"
t = Date.strptime(start_datetime, '%Y-%m-%d')
t.strftime('00:00_%Y%m%d') # => "00:00_20160609"
Upvotes: 0