views:

243

answers:

1

Hello,

I have to validate the format of a date string coming from a csv file. I use the csvReader(au.com.bytecode.opencsv.CSVReader) parser. Below is the code I use to get the data from the csv reader and change it to a date format.

def String strToDate = csvrow[monatVal]

myDate = new Date().parse("dd.MM.yy HH:mm",strToDate)

The problem is that in the CSV file there exists a date entry for eg. '41.01.10 12:22', i have the following when i print 'myDate'

myDate = '10.02.10 12:22' --> Its adding 10 days to the Feb month.

I would like here a validation check for the date format. Is there a way to check the dateString while parsing?

Thanks in advance, Sudheer

Parse, it is probably best as a static method, i.e. Date.parse( format, input ), that returns a new Date instance – right?

+2  A: 

The method you're using to do the date parsing is deprecated. You should use DateFormat.parse() or SimpleDateFormat.parse() instead.

These classes have a setLenient(boolean) method. If you set lenient to false then you won't get the 10th February when you parse 41.01, instead the parser will throw a ParseException.

Run the following code to see what I mean

def dateParser = new java.text.SimpleDateFormat("dd.MM.yy HH:mm")

// If the next line is removed the date will be parsed to 10 February instead of 
// throwing a ParseException
dateParser.lenient = false  

dateParser.parse('41.01.10 12:22')
Don
Thanks Don. Setting lenient to false. But instead of giving a right format i give something like dateParser.parse('41.01.10 12:22:34') its not recognising that the seconds pattern is not the pattern set as the SimpleDateFormat. How do i check this? I tried already applypattern. Dosent change much though.
sudheer
I'm not sure if SimpleDateFormat supports this. Maybe you could just check if the length of the pattern string and the length of the date string are the same before trying to parse the date string
Don