Reputation: 133
I have a date string that I need to simplify in Ruby:
2008-10-09 20:30:40
I only want the day portion:
2008-10-09
I'm looking for a gsub line that will strip everything after a set number of characters or the first whitespace.
Upvotes: 3
Views: 2366
Reputation: 198324
Literal solution:
date.gsub(/(.{10}).*/, '\1')
date.gsub(/\s.*/, '')
date[0, 10]
Better solution: Treat it as a DateTime object - then you can format it as you wish:
date = DateTime.now
date.strftime("%m-%d-%Y") # America
date.strftime("%d-%m-%Y") # Europe
Upvotes: 2
Reputation: 160551
I prefer to use as simple a solution as I can. Using gsub
is needlessly complex. Either of these will do it:
str = '2008-10-09 20:30:40'
str[/(\S+)/, 1] #=> "2008-10-09"
str[0, 10] #=> "2008-10-09"
Upvotes: 6
Reputation: 168101
If the format is consistantly like that,
'2008-10-09 20:30:40'[/[-\d]+/] # => "2008-10-19"
Upvotes: 1