开发者

Validating date format inside a groovy controller

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().par开发者_如何学Cse("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?


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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜