AntonB
AntonB

Reputation: 2853

Ruby string to date time format

I have multiple dates coming in from user input, examples:

MM-DD-YYYY

6-3-1975

MM/DD/YYYY

4/23/1967

using the ruby built in require 'time'

and trying to Time.parse("4/23/1967")

gives me the error time.rb : argument out of range.

Any solutions to convert different user inputs with either dashes or slashes to parse?

Upvotes: 3

Views: 2010

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 339422

Replace delimiter

Just replace the unwanted delimiter with the wanted delimiter.

In Java syntax:

String input = "4/23/1967".replace ( "/" , "-" ) ;  // Results in "4-23-1967". 

java.time

Use date.time classes for your date-time handling.

Define a formatting pattern to match.

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "M-d-uuuu" ) ;

And parse.

LocalDate ld = LocalDate.parse ( input , formatter ) ;

Upvotes: 0

AntonB
AntonB

Reputation: 2853

Solution:

require 'date'

userDate = "4-23-1967"
readDate = Date.strptime(userDate, "%m-%d-%Y")
convertedDate = readDate.strftime("%-m/%-d/%Y")
puts convertedDate

OUTPUT: 4/23/1967

Upvotes: 3

jkeuhlen
jkeuhlen

Reputation: 4517

It sounds like you should use gsub to replace the characters you don't want with the ones you do.

input = "6-3-1975"
sanitized_input = input.gsub(/[- ]/, '/')

Inside the square brackets you can put any delimiter that your users are including that you don't want.

Upvotes: -1

Jing Li
Jing Li

Reputation: 15116

Try below:

Time.parse("23/4/1967")
#=> 1967-04-23 00:00:00 +0100
Time.parse("3-6-1975")
#=> 1975-06-03 00:00:00 +0100

So the problem is that your month and day order is reversed.

Upvotes: 1

Related Questions