Redarding date i want to identify the formate of input date ex: input: 10-12-1995 output: dd-mm-yyyy

#1

if my inputs is 10/12/2019 my expected outputs is dd/mm/yyyy
if my inputs is 2019/12/10 my expected outputs is yyyy/mm/dd
if my inputs is 12/10/2019 my expected outputs is mm/dd/yyyy
like above i want outputs

i want to identify the formate of input date
ex:
input: 10-12-1995
output: dd-mm-yyyy

#2

There’s no way of detecting the correct date and month AFAIK…

Because the month can be 12 and the date can be 1, or the date can be 1 and the month 12. You can’t tell which one is month and which one is day!

Consider the date: 01/28/2018
As a human you can tell me that the day is 28, month is 01, and the year is 2018, and you can code it for date > 12.

But consider the date: 02/04/2018
Again, you can tell me that 2018 is the year. But is 02 the day or 04 the day? Neither you can distinguish between the day and the month here, nor your code can - leading to nasty bugs :beetle:

You can surely do it with only day and year and month and year:

def detect(f)
	f.scan(/[^0-9]/).join.tap { |x| raise(RuntimeError, 'Invalid Format') if x.empty? }.then { |x| f.split(x) }
		.then { |x| x.index { |i| i.length == 4 }.to_i < x.index { |i| /[12]/ === i.length.to_s }.to_i ? 'yyyy/mm' : 'mm/yyyy' }
end

p detect('1997.11')    # => "yyyy/mm"
p detect('1999/10')    # => "yyyy/mm"
p detect('12-2019')    # => "mm/yyyy"
p detect('12|1111')    # => "mm/yyyy"

In this case the year has to have 4 characters. You can’t simply have year 1 and month 12!

Also, if you are building GUI application, the format of the date is hard-coded, it’s not detected! I know detecting the date will give some flexibility but I think it’s not possible!

#3

This is rather simple guys. Although not perfect with error control here’s the back bone you are looking for.
def date_format
date = Time.new
@dd = date.day
@mm = date.month
@yr = date.year

$a ="#{@dd}-#{@mm}-#{@yr}"
$b = #repeat different format patterns in global variables
$usr-input =nill
puts "input date: " ; $usr_input = gets.chomp
if $usr_input.to_s == $a
puts “user used blaa blaa blaa format”
end

#repeat if statements for each format type

end
date_format

1560208008816142267245|375x500

#4

Keep in mind that the Time.month (or in this case date.month). Will only display a single digits until the 10th month. It won’t output “02” for example.
If you want this then you will have to physically incode it. With some code to check the length and another conditional statement it won’t break. Example
month_digit =Time.month.to_s.length
If month_digit == 1
puts "0#{Time.month}/#{Time.day}/#{Time.year}
end
If month_digit== 2
puts “#{Time.month}/#{Time.day}/#{Time.year}”
end

#5

#6

Thank you so much giving the time for solution

#7

Thank you so much for your solution

1 Like