Groovy字符串到日期 [英] Groovy String to Date

查看:2029
本文介绍了Groovy字符串到日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Groovy编码这个。



我目前正在尝试转换一个我必须做的日期的字符串,而不用做任何太乏味的事情。

  String theDate =28/09/2010 16:02:43; 
def newdate = new Date()。parse(d / M / yyyy H:m:s,theDate)

输出:

  Tue Aug 10 16:02:43 PST 2010 

上面的代码工作得很好,但是当我的字符串更改为如下所示:

  String testDate =Tue Aug 10 16:02:43 PST 2010
def newerdate = new Date()。parse(d / M / yyyy H: m:s,testDate)

它告诉我Tue没有这样的价值。我试图在日期的解析中抛出一个'E',但是它表示日期无法被解析。



有人可以解释我应该怎么去解析第二个例子?

解决方案

parse()的第一个参数是预期的格式。您必须将其更改为 Date.parse(E MMM dd H:m:s z yyyy,testDate)才能正常工作。 (注意,您不需要创建一个新的Date对象,它是一个静态方法)



如果您不提前知道什么格式,您将必须找到一个特殊的解析库。在Ruby中有一个名为 Chronic 的库,但是我并不知道Groovy的等价物。 编辑:库中有一个名为 jChronic 的Java端口,您可能需要检查出来。


I am coding this with Groovy

I am currently trying to convert a string that I have to a date without having to do anything too tedious.

String theDate = "28/09/2010 16:02:43";
def newdate = new Date().parse("d/M/yyyy H:m:s", theDate)

Output:

Tue Aug 10 16:02:43 PST 2010

The above code works just fine, however when my string changes to something like:

String testDate = "Tue Aug 10 16:02:43 PST 2010"
def newerdate = new Date().parse("d/M/yyyy H:m:s", testDate)

It tells me that "there is no such value for Tue". I tried to throw an 'E' in the parse for the date but it said the date was not able to be parsed.

Can someone explain how I should go about parsing the second example?

解决方案

The first argument to parse() is the expected format. You have to change that to Date.parse("E MMM dd H:m:s z yyyy", testDate) for it to work. (Note you don't need to create a new Date object, it's a static method)

If you don't know in advance what format, you'll have to find a special parsing library for that. In Ruby there's a library called Chronic, but I'm not aware of a Groovy equivalent. Edit: There is a Java port of the library called jChronic, you might want to check it out.

这篇关于Groovy字符串到日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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