迄今为止的 Groovy 字符串 [英] Groovy String to Date

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

问题描述

我正在用 Groovy 编写代码

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)

输出:

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)

它告诉我周二没有这样的价值".我试图在日期的解析中抛出一个E",但它说无法解析日期.

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?

推荐答案

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

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)

如果您事先不知道是什么格式,则必须为此找到一个特殊的解析库.在 Ruby 中有一个名为 Chronic 的库,但我不知道 Groovy 的等价物.编辑:有一个名为 jChronic 的库的 Java 端口,您可能想要去看看.

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天全站免登陆