如何将此格式的日期(Tue Jul 13 00:00:00 CEST 2010)转换为 Java 日期(该字符串来自露天属性)

发布于 2024-11-06 02:55:57 字数 3397 浏览 4 评论 0原文

我正在管理一个来自 Alfresco Properties 且指定的日期(2010 年 CEST 7 月 13 日星期二 00:00:00),我需要将其转换为 Java 日期...我环顾四周,发现了数百万个日期各种字符串到日期转换表单的帖子以及此页面,所以我尝试了这样的事情:

private static final DateFormat alfrescoDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date dataRispostaDate = alfrescoDateFormat.parse(dataRisposta);

但它引发了异常。(异常是(SSollevata un'eccezione durante la gestione della data: java.text.ParseException: Unparseable date: "Tue Jul 13 00:00:00 CEST 2011")。

我发布完整的代码:

        try {
            QName currDocTypeQName = (QName) nodeService.getType(doc);
            log.error("QName:["+currDocTypeQName.toString()+"]");
            if (currDocTypeQName != null) {
                String codAtto = AlfrescoConstants.getCodAttoFromQName(currDocTypeQName.toString());
                log.error("codAtto:["+codAtto+"]");
                if (codAtto.equals(AlfrescoConstants.COD_IQT)){
                    List<ChildAssociationRef> risposteAssociate = nodeService.getChildAssocs(doc, AlfrescoConstants.QN_RISPOSTEASSOCIATE, RegexQNamePattern.MATCH_ALL);
                    for (ChildAssociationRef childAssocRef : risposteAssociate) {
                        // Vado a prendere il nodo
                        NodeRef risposta = childAssocRef.getChildRef();
                        String dataRisposta = (nodeService.getProperty(risposta, AlfrescoConstants.QN_DATA_RISPOSTA)).toString();
                        log.error("dataRisposta:["+dataRisposta+"]");
                        if (!dataRisposta.isEmpty()){
                            try {
                                Date dataDa = dmyFormat.parse(req.getParameter("dataDa"));
                                log.error("dataDa:["+dataDa.toString()+"]");
                                Date dataA = dmyFormat.parse(req.getParameter("dataA"));
                                log.error("dataA:["+dataA.toString()+"]");
                                Date dataRispostaDate = alfrescoDateFormat.parse(dataRisposta);
                                log.error("dataRispostaDate:["+dataRispostaDate.toString()+"]");

                                if (dataRispostaDate.after(dataDa) && dataRispostaDate.before(dataA)){
                                    results.add(doc);
                                    log.error("La data risposta  è compresa tra le date specificate");
                                }else{
                                    log.error("La data risposta non è compresa tra le date specificate");
                                }
                            } catch (ParseException e) {
                                log.error("Sollevata un'eccezione durante la gestione della data: " + e);
                                throw new RuntimeException("Formato data non valido");
                            }
                        }else{
                            log.error("La data risposta non è specificata");
                        }
                    }
                }else{
                    results.add(doc);
                }
            }
        } catch (Exception e) {
            log.error("Sollevata un'eccezione durante la gestione del codice atto nel webscript nicola: " + e);
        }

有人可以帮忙吗?

i'm managing a date that comes from an Alfresco Properties and is in the specified (Tue Jul 13 00:00:00 CEST 2010) and i need to convert it to a Java date...i've looked around and found millions of posts for various string to date conversion form and also this page and so i tried something like this:

private static final DateFormat alfrescoDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date dataRispostaDate = alfrescoDateFormat.parse(dataRisposta);

But it throws an exception.(The exception is (SSollevata un'eccezione durante la gestione della data: java.text.ParseException: Unparseable date: "Tue Jul 13 00:00:00 CEST 2011").

I post the complete code:

        try {
            QName currDocTypeQName = (QName) nodeService.getType(doc);
            log.error("QName:["+currDocTypeQName.toString()+"]");
            if (currDocTypeQName != null) {
                String codAtto = AlfrescoConstants.getCodAttoFromQName(currDocTypeQName.toString());
                log.error("codAtto:["+codAtto+"]");
                if (codAtto.equals(AlfrescoConstants.COD_IQT)){
                    List<ChildAssociationRef> risposteAssociate = nodeService.getChildAssocs(doc, AlfrescoConstants.QN_RISPOSTEASSOCIATE, RegexQNamePattern.MATCH_ALL);
                    for (ChildAssociationRef childAssocRef : risposteAssociate) {
                        // Vado a prendere il nodo
                        NodeRef risposta = childAssocRef.getChildRef();
                        String dataRisposta = (nodeService.getProperty(risposta, AlfrescoConstants.QN_DATA_RISPOSTA)).toString();
                        log.error("dataRisposta:["+dataRisposta+"]");
                        if (!dataRisposta.isEmpty()){
                            try {
                                Date dataDa = dmyFormat.parse(req.getParameter("dataDa"));
                                log.error("dataDa:["+dataDa.toString()+"]");
                                Date dataA = dmyFormat.parse(req.getParameter("dataA"));
                                log.error("dataA:["+dataA.toString()+"]");
                                Date dataRispostaDate = alfrescoDateFormat.parse(dataRisposta);
                                log.error("dataRispostaDate:["+dataRispostaDate.toString()+"]");

                                if (dataRispostaDate.after(dataDa) && dataRispostaDate.before(dataA)){
                                    results.add(doc);
                                    log.error("La data risposta  è compresa tra le date specificate");
                                }else{
                                    log.error("La data risposta non è compresa tra le date specificate");
                                }
                            } catch (ParseException e) {
                                log.error("Sollevata un'eccezione durante la gestione della data: " + e);
                                throw new RuntimeException("Formato data non valido");
                            }
                        }else{
                            log.error("La data risposta non è specificata");
                        }
                    }
                }else{
                    results.add(doc);
                }
            }
        } catch (Exception e) {
            log.error("Sollevata un'eccezione durante la gestione del codice atto nel webscript nicola: " + e);
        }

Anyone can help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

暮年 2024-11-13 02:55:57

基本上你的问题是你正在使用SimpleDateFormat(String pattern) 构造函数,其中 javadoc 表示:

使用构造 SimpleDateFormat
给定的模式和默认日期
默认区域设置的格式符号。

如果您尝试使用此代码:

DateFormat osLocalizedDateFormat = new SimpleDateFormat("MMMM EEEE");
System.out.println(osLocalizedDateFormat.format(new Date()))

您会注意到它会根据您的区域设置打印月份和星期几的标题。

问题的解决方案是使用 SimpleDateFormat(String pattern, Locale locale) 构造函数:

DateFormat dateFormat = new SimpleDateFormat(
            "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
dateFormat.parse("Tue Jul 13 00:00:00 CEST 2011");
System.out.println(dateFormat.format(new Date()));

Basically your problem is that you are using a SimpleDateFormat(String pattern) constructor, where javadoc says:

Constructs a SimpleDateFormat using
the given pattern and the default date
format symbols for the default locale.

And if you try using this code:

DateFormat osLocalizedDateFormat = new SimpleDateFormat("MMMM EEEE");
System.out.println(osLocalizedDateFormat.format(new Date()))

you will notice that it prints you month and day of the week titles based on your locale.

Solution to your problem is to override default Date locale using SimpleDateFormat(String pattern, Locale locale) constructor:

DateFormat dateFormat = new SimpleDateFormat(
            "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
dateFormat.parse("Tue Jul 13 00:00:00 CEST 2011");
System.out.println(dateFormat.format(new Date()));
烏雲後面有陽光 2024-11-13 02:55:57

太长了;博士

ZonedDateTime.parse(                     // Produce a `java.time.ZonedDateTime` object.
    "Wed Jul 13 00:00:00 CEST 2011" ,    // Corrected `Tue` to `Wed`.
    DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss zzz uuuu" , Locale.US  ) 
)

2011-07-13T00:00+02:00[欧洲/巴黎]

错误数据:Wed vs Tue

您输入字符串 Tue Jul 13 00:00:00 CEST 2011 无效。 2011 年 7 月 13 日是星期三,不是星期二

String input = "Wed Jul 13 00:00:00 CEST 2011" ;  // Corrected `Tue` to `Wed`.

屏幕截图Duck Duck Go 搜索引擎中的 2011 年 7 月日历

java.time

现代方法使用 java.time 类,而不是其他答案中看到的麻烦的旧遗留日期时间类。

定义格式模式以匹配您的输入字符串。请注意 区域设置,它定义了用于解析月份名称和星期名称的人类语言。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss zzz uuuu" , Locale.US  );
ZonedDateTime zdt = ZonedDateTime.parse( input , f  );

zdt.toString(): 2011-07-13T00:00+02:00[欧洲/巴黎]

时区

您的 CEST 是一个伪时区,而不是真正的时区。切勿使用这些。它们不是标准化的,甚至不是唯一的(!)。

ZonedDateTime 类将做出勇敢的努力来猜测这样一个 3-4 个字符的伪区域背后的意图。您的 CEST 恰好在这里工作,解释为 Europe/Paris 时区。但你不能指望猜测 100% 成功。相反,完全避免此类伪区域

大陆/地区正确的时区名称代码>,例如美国/蒙特利尔非洲/卡萨布兰卡,或太平洋/奥克兰

ZoneId z = ZoneId.of( "Europe/Paris" );  // https://time.is/Paris
LocalDate today = LocalDate.now( z );  // Current date varies around the globe by zone.

ISO 8601

您输入字符串的格式很糟糕。将日期时间值序列化为文本时,仅使用标准 ISO 8601 格式。

ZonedDateTime 类通过在方括号中附加时区名称来明智地扩展标准格式,如上面的示例所示。


关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历,& SimpleDateFormat

Joda-Time 项目,现位于 维护模式,建议迁移到 java.time 类。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 IntervalYearWeekYearQuarter更多

tl;dr

ZonedDateTime.parse(                     // Produce a `java.time.ZonedDateTime` object.
    "Wed Jul 13 00:00:00 CEST 2011" ,    // Corrected `Tue` to `Wed`.
    DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss zzz uuuu" , Locale.US  ) 
)

2011-07-13T00:00+02:00[Europe/Paris]

Bad data: Wed vs Tue

You input string Tue Jul 13 00:00:00 CEST 2011 is invalid. July 13 of 2011 was a Wednesday, not a Tuesday.

String input = "Wed Jul 13 00:00:00 CEST 2011" ;  // Corrected `Tue` to `Wed`.

screen shot of July 2011 calendar in Duck Duck Go search engine

java.time

The modern approach uses the java.time classes rather than the troublesome old legacy date-time classes seen in other Answers.

Define a formatting pattern to match your input string. Notice the Locale, which defines the human language to be used in parsing name of month and name of day-of-week.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss zzz uuuu" , Locale.US  );
ZonedDateTime zdt = ZonedDateTime.parse( input , f  );

zdt.toString(): 2011-07-13T00:00+02:00[Europe/Paris]

Time zone

Your CEST is a pseudo-zone, not a true time zone. Never use these. They are not standardized, and are not even unique(!).

The ZonedDateTime class will make a valiant effort at guessing the intention behind such a 3-4 character pseudo-zone. Your CEST happened to work here, interpreted as Europe/Paris time zone. But you cannot rely on the guess being 100% successful. Instead, avoid such pseudo-zones entirely.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland.

ZoneId z = ZoneId.of( "Europe/Paris" );  // https://time.is/Paris
LocalDate today = LocalDate.now( z );  // Current date varies around the globe by zone.

ISO 8601

Your input string’s format is terrible. When serializing date-time values as text, use only the standard ISO 8601 formats.

The ZonedDateTime class wisely extends the standard format by appending the name of the time zone in square brackets as seen in examples above.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

赴月观长安 2024-11-13 02:55:57

根据您的评论,我相信您的属性实际上是 d:dated:datetime 类型。如果是这样,该属性将已经作为 java Date 对象从 Alfresco 返回。所以,您需要做的就是:

  NodeRef risposta = childAssocRef.getChildRef();
  Date dataRisposta = (Date)nodeService.getProperty(risposta, AlfrescoConstants.QN_DATA_RISPOSTA);

Based on your comments, I believe that your property is actually of type d:date or d:datetime. If so, the property will already be coming back from Alfresco as a java Date object. So, all you'd need to do is:

  NodeRef risposta = childAssocRef.getChildRef();
  Date dataRisposta = (Date)nodeService.getProperty(risposta, AlfrescoConstants.QN_DATA_RISPOSTA);
失去的东西太少 2024-11-13 02:55:57

问题是 CEST 不是 Java 支持的时区。您可以使用“CST”。

TimeZone 的 Javadoc 注释:

三字母时区 ID
为了与 JDK 1.1.x 兼容,还支持一些其他三字母时区 ID(例如“PST”、“CTT”、“AST”)。但是,不推荐使用它们,因为相同的缩写通常用于多个时区(例如,“CST”可能是美国“中部标准时间”和“中国标准时间”),而 Java平台只能识别其中之一。

对于三/四字母时区支持,我建议您尝试 JodaTime,它可能会做得更好。


String dataRisposta = "Tue Jul 13 00:00:00 CST 2010";
Date dataRispostaDate = alfrescoDateFormat.parse(dataRisposta);
System.out.println(dataRispostaDate);

版画

Tue Jul 13 07:00:00 BST 2010

String[] ids = TimeZone.getAvailableIDs();
Arrays.sort(ids);
for (String id : ids) {
    System.out.println(id);
}

版画

...
CAT
CET
CNT
CST
CST6CDT
CTT
...

The problem is that CEST is not a timezone Java supports. You can use "CST".

The Javadoc for TimeZone notes:

Three-letter time zone IDs
For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.

For three/four letter timezone support I suggest you try JodaTime which may do a better job.


String dataRisposta = "Tue Jul 13 00:00:00 CST 2010";
Date dataRispostaDate = alfrescoDateFormat.parse(dataRisposta);
System.out.println(dataRispostaDate);

prints

Tue Jul 13 07:00:00 BST 2010

String[] ids = TimeZone.getAvailableIDs();
Arrays.sort(ids);
for (String id : ids) {
    System.out.println(id);
}

prints

...
CAT
CET
CNT
CST
CST6CDT
CTT
...
浪推晚风 2024-11-13 02:55:57

试试这个功能我也遇到了同样的问题。

public String getMyDate(String myDate, String requiredFormat, String mycurrentFormat) {
    DateFormat dateFormat = new SimpleDateFormat(returnFormat);
    Date date = null;
    String returnValue = "";
    try {
        date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
        returnValue = dateFormat.format(date);
    } catch (ParseException e) {
        returnValue = myDate;
    }
    return returnValue;
}

示例:

Wed May 06 13:01:29 EDT 2020 即“EEE MMM dd HH:mm:ss zzz yyyy”是 mycurrentFormat

4.May.2020 即“d.MMM.yyyy”是我的 requiredFormat

Date date = new Date();

getMyDate(date.toString(), "d.MMM.yyyy", "EEE MMM dd HH:mm:ss zzz yyyy")

Try this function I had the same issue.

public String getMyDate(String myDate, String requiredFormat, String mycurrentFormat) {
    DateFormat dateFormat = new SimpleDateFormat(returnFormat);
    Date date = null;
    String returnValue = "";
    try {
        date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
        returnValue = dateFormat.format(date);
    } catch (ParseException e) {
        returnValue = myDate;
    }
    return returnValue;
}

Example:

Wed May 06 13:01:29 EDT 2020 i.e "EEE MMM dd HH:mm:ss zzz yyyy" is mycurrentFormat

4.May.2020 i.e. "d.MMM.yyyy" is my requiredFormat

Date date = new Date();

getMyDate(date.toString(), "d.MMM.yyyy", "EEE MMM dd HH:mm:ss zzz yyyy")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文