Checking the date format inside the groovy controller

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

def String strToDate = csvrow[monatVal]

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

The problem is that there is a date entry in the CSV file, for example. '41 .01.10 12:22 ', I have the following when I type' myDate '

myDate = '10.02.10 12:22' β†’ It adds 10 days to the month of February.

I would like to check the date format check here. Is there any way to check dateString during parsing?

Thanks in advance, Sudheer

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

+4
source share
1 answer

The method you use to parse the date is deprecated. Instead, you should use DateFormat.parse() or SimpleDateFormat.parse() .

These classes have a setLenient(boolean) method. If you set lenient to false, you will not receive February 10 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') 
+7
source

All Articles