【问题标题】:Reformating string date with TimeZone使用 TimeZone 格式化字符串日期
【发布时间】:2012-10-20 17:55:54
【问题描述】:

我对 Groovy 还很陌生(但已经很喜欢它了)。我对编码并不陌生,但到目前为止还没有太多经验。

我在做什么? 我正在从 excel 文件中提取某些信息以从中创建 XML (SOAP) 消息以将其转发到 Web 服务。到目前为止一切正常日期转换除外。

我将字符串日期保存到 var

odate = 'Wed Oct 31 00:00:00 CET 2012' 

我需要将此日期重新格式化为类似

"10/31/2012 10:09:00" (MM/dd/yyyy HH:mm:ss)

我试图将日期解析为mentioned in another question,但我得到的只是一个例外。

String odate = 'Wed Oct 31 00:00:00 CET 2012'
def parsedodate = new Date().parse('E MMM dd H:m:s z yyyy', odate)

println parsedodate.format('MM/dd/yyyy h:m:s')

抛出异常 31.10.2012 10:18:25 org.codehaus.groovy.runtime.StackTraceUtils 清理

警告:清理堆栈跟踪:

java.text.ParseException:无法解析的日期:“Wed Oct 31 00:00:00 CET 2012”


现在经过一些阅读和几轮反复试验,我发现解析方法似乎只能解释德国日期。在手动将字符串日期更改为德语格式(这是我所在的位置)之后,以下工作。

String odate = 'Mi Okt 31 00:00:00 2012' //Mi = Wednesday, Okt = October, removed timezone
def parsedodate  = new Date().parse('E MMM dd H:m:s yyyy', odate) // removed the z
println parsedodate .format('MM/dd/yyyy h:m:s')

但是,我需要解析器接受英文日期格式。 我该怎么办(错)?

【问题讨论】:

    标签: parsing date groovy timezone format


    【解决方案1】:

    您的问题的完整解决方案是:

    import java.text.SimpleDateFormat
    odate="Wed Oct 31 00:00:00 CET 2012"
    
    englishPattern="E MMM dd H:m:s z yyyy"
    
    SimpleDateFormat englishDateFormat = new SimpleDateFormat( englishPattern , Locale.ENGLISH);
    //SimpleDateFormat germanDateFormat = new SimpleDateFormat( germanPattern , Locale.GERMAN);
    
    Date englishDate = englishDateFormat.parse( odate );
    //Date germanDate = germanDateFormat.parse( odate );
    
    String englishOutput = englishDate .format( englishPattern );
    //String germanOutput = germanDate .format( germanPattern );
    
    englishDate.format("MM/dd/yyyy hh:mm:ss")
    

    【讨论】:

    • 感谢您提供更多信息。
    【解决方案2】:

    您将需要使用一些 Java 来访问支持区域设置的 SimpleDateFormat 实例。

    SimpleDateFormat englishDateFormat = new SimpleDateFormat( englishPattern , Locale.ENGLISH);
    SimpleDateFormat germanDateFormat = new SimpleDateFormat( germanPattern , Locale.GERMAN);
    
    Date englishDate = englishDateFormat.parse( odate );
    Date germanDate = germanDateFormat.parse( odate );
    
    String englishOutput = englishDate .format( englishPattern );
    String germanOutput = germanDate .format( germanPattern );
    

    【讨论】:

    • 感谢您的提示。这就是我想要的。
    猜你喜欢
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多