string 迄今为止的 Groovy 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3817862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:51:44  来源:igfitidea点击:

Groovy String to Date

stringparsingdategroovy

提问by StartingGroovy

I am coding this with Groovy

我正在用 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.

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

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

有人可以解释我应该如何解析第二个示例吗?

回答by Mark Thomas

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)

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

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.

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

回答by gcores

Try this:

尝试这个:

def date = Date.parse("E MMM dd H:m:s z yyyy", dateStr)

Here are the patterns to format the dates

这是格式化日期模式

回答by ataylor

JChronic is your best choice. Here's an example that adds a .fromString()method to the Date class that parses just about anything you can throw at it:

JChronic 是您的最佳选择。这是一个.fromString()向 Date 类添加一个方法的示例,该方法可以解析您可以抛出的任何内容:

Date.metaClass.'static'.fromString = { str ->
    com.mdimension.jchronic.Chronic.parse(str).beginCalendar.time
}

You can call it like this:

你可以这样称呼它:

println Date.fromString("Tue Aug 10 16:02:43 PST 2010")
println Date.fromString("july 1, 2012")
println Date.fromString("next tuesday")

回答by Doug Paul

Googling around for Groovy ways to "cast" a Stringto a Date, I came across this article: http://www.goodercode.com/wp/intercept-method-calls-groovy-type-conversion/

谷歌搜索 Groovy 方法将 a 转换String为 a Date,我发现了这篇文章:http: //www.goodercode.com/wp/intercept-method-calls-groovy-type-conversion/

The author uses Groovy metaMethods to allow dynamically extending the behavior of any class' asTypemethod. Here is the code from the website.

作者使用 Groovy 元方法允许动态扩展任何类的asType方法的行为。这是来自网站的代码。

class Convert {
    private from
    private to

    private Convert(clazz) { from = clazz }
    static def from(clazz) {
        new Convert(clazz)
    }

    def to(clazz) {
        to = clazz
        return this
    }

    def using(closure) {
        def originalAsType = from.metaClass.getMetaMethod('asType', [] as Class[])
        from.metaClass.asType = { Class clazz ->
            if( clazz == to ) {
                closure.setProperty('value', delegate)
                closure(delegate)
            } else {
                originalAsType.doMethodInvoke(delegate, clazz)
            }
        }
    }
}

They provide a Convertclass that wraps the Groovy complexity, making it trivial to add custom as-based type conversion from any type to any other:

它们提供了一个Convert包含 Groovy 复杂性的类,使得添加as从任何类型到任何其他类型的基于自定义的类型转换变得微不足道:

Convert.from( String ).to( Date ).using { new java.text.SimpleDateFormat('MM-dd-yyyy').parse(value) }

def christmas = '12-25-2010' as Date

It's a convenient and powerful solution, but I wouldn't recommend it to someone who isn't familiar with the tradeoffs and pitfalls of tinkering with metaClasses.

这是一个方便且强大的解决方案,但我不会向不熟悉修改元类的权衡和陷阱的人推荐它。

回答by Abdennour TOUMI

Date#parseis deprecated . The alternative is :

Date#parse已弃用。替代方案是:

java.text.DateFormat#parse 

thereFore :

所以 :

 new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)

Note that SimpleDateFormat is an implementation of DateFormat

注意 SimpleDateFormat 是 DateFormat 的一个实现

回答by Ibrahim.H

I think the best easy way in this case is to use parseToStringDatewhich a one of the Groovy JDK enhancements:

我认为在这种情况下最好的简单方法是使用parseToStringDate这是 Groovy JDK 增强功能之一:

Parse a String matching the pattern EEE MMM dd HH:mm:ss zzz yyyy containing US-locale-constants only (e.g. Sat for Saturdays). Such a string is generated by the toString method of Date

解析与模式 EEE MMM dd HH:mm:ss zzz yyyy 匹配的字符串,仅包含美国语言环境常量(例如周六的周六)。这样的字符串是Date的toString方法生成的

Example:

例子:

println (Date.parseToStringDate("Tue Aug 10 16:02:43 PST 2010").format('MM-dd-yyyy'))?

Hope this helps.

希望这可以帮助。

回答by Tung

Below is the way we are going within our developing application.

以下是我们在开发应用程序中的工作方式。

import java.text.SimpleDateFormat

String newDateAdded = "2018-11-11T09:30:31"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
Date dateAdded = dateFormat.parse(newDateAdded)

println(dateAdded)

The output looks like

输出看起来像

Sun Nov 11 09:30:31 GMT 2018

In your example, we could adjust a bit to meet your need. If I were you, I will do:

在您的示例中,我们可以稍微调整一下以满足您的需要。如果我是你,我会这样做:

String datePattern = "d/M/yyyy H:m:s"
String theDate = "28/09/2010 16:02:43"
SimpleDateFormat df = new SimpleDateFormat(datePattern)
println df.parse(theDate)

I hope this would help you much.

我希望这会对你有很大帮助。