验证groovy控制器内的日期格式 [英] Validating date format inside a groovy controller

查看:170
本文介绍了验证groovy控制器内的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须验证来自csv文件的日期字符串的格式。我使用csvReader(au.com.bytecode.opencsv.CSVReader)解析器。以下是用于从csv读取器获取数据并将其更改为日期格式的代码。



def String strToDate = csvrow [monatVal]



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



问题是在CSV文件中存在一个例如日期条目。 '41 .01.10 12:22',当我打印'myDate'时,我有以下的一些:

myDate = '10 .02.10 12:22' - >它在二月份添加了10天。



我想在这里验证日期格式。在解析时有没有办法检查dateString?



提前感谢
Sudheer



解析,最好是一个静态方法,即Date.parse(format,input),它返回一个新的Date实例 - 对吗?

解决方案

做日期解析已被弃用。您应该使用 DateFormat.parse() SimpleDateFormat.parse()



这些类有一个 setLenient(boolean)方法。如果你设置宽松为false,那么当你解析 41.01 时,你不会得到二十分之二,而是解析器会抛出一个ParseException。



运行以下代码查看我的意思

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

//如果下一行被删除,日期将被解析为二月二十日而不是
//抛出一个ParseException
dateParser .lenient = false

dateParser.parse('41 .01.10 12:22')


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?

解决方案

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

这篇关于验证groovy控制器内的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆