Java SimpleDateFormat pattern for W3C XML dates with timezone [duplicate]

扶醉桌前 提交于 2019-12-17 07:26:33

问题


I am trying to parse a W3C XML Schema date like the following

"2012-05-15T07:08:09+03:00"

which complies with the ISO 8601 version of the W3C XML Schema dateTime specification.

In the above date, the timezone identifier is "+03:00", but no SimpleDateFormat pattern apparently exists to represent it.

If the timezone were "+0300", then Z (uppercase) would be applicable and the SimpleDateFormat pattern would be

yyyy-MM-dd'T'HH:mm:ssZ

Similarly, if the timezone were "GMT+03:00", then z (lowercase) would be applicable and the SimpleDateFormat pattern would be

yyyy-MM-dd'T'HH:mm:ssz

(uppercase 'Z' also works, by the way).

So, is there a SimpleDateFormat pattern or workaround to represent the above date without preprocessing of the date string?


回答1:


How about something like:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"){ 
    public Date parse(String source,ParsePosition pos) {    
        return super.parse(source.replaceFirst(":(?=[0-9]{2}$)",""),pos);
    }
};



回答2:


If you use Java 7+, this pattern should work (X is for the ISO 8601 time zone):

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");



回答3:


Hmmm the date format looks like XML datetime datatype format? If it is XML datetime datatype format you can use javax.xml.datatype.DatatypeFactory to create XMLGregorianCalendar

DatatypeFactory
  .newInstance()
  .newXMLGregorianCalendar("2012-05-15T07:08:09+03:00");

The above call returns instance of XMLGregorianCalendar you can use the object to convert to other Java datetime objects like GregorianCalendar.




回答4:


No, there is no workaround to make SimpleDateFormat understand this format without preprocessing the string (for example by removing the : from the string). (edit: except if you're using Java 7 or newer as noted by assylias).

It looks like you're trying to parse strings in the standard XML format for dates and times (ISO 8601). I would recommend using the Joda Time library which has support for this format.

If you can't or don't want to use Joda Time for some reason, then you can use classes from the package javax.xml.datatype to parse and format timestamps in this format. For example:

DatatypeFactory factory = DatatypeFactory.newInstance();

// Parses a string in ISO 8601 format to an XMLGregorianCalendar
XMLGregorianCalendar xmlCal = factory.newXMLGregorianCalendar("2012-05-16T10:39:00+03:00");

// Convert it to a regular java.util.Calendar
Calendar cal = xmlCal.toGregorianCalendar();



回答5:


use Apache commons DateUtils with possible patterns. Ex:

private static final String[] DATE_FORMATS = new String[] {
            "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ssz",
            "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-ddz", "yyyy-MM-ddZ" };


    public Date parse(String date) {

        Date parsedDate = null;
        try {
            parsedDate = DateUtils.parseDate(date, DATE_FORMATS);
        } catch (ParseException e) {
            logger.error("dates should be in valid format" + e);
            return null;
        }
               return parsedDate;
              }



回答6:


The best way is to Use the Joda's

org.joda.time.format.ISODateTimeFormat

Regards,




回答7:


With regards to SimpleDateFormat you have already mentioned the format patterns that are available and they are defined in: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

If you want to do more with your Date then GregorianCalendar gives you more options, e.g.:

TimeZone zone = TimeZone.getTimeZone(TimeZone.getTimeZone("GMT-8").getID());
GregorianCalendar calendar = new GregorianCalendar(zone);
calendar.setTime(new Date(SomeDate));



回答8:


You can try something like:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
Date date = df.parse(stringDate.replaceAll("\\+", "GMT+"));



回答9:


I am not quite sure whether this will work for you or not. But here the code I have tried while converting date from one timezone to another timezone. May some part of the code can help you.

public Date convertToUserTimezone(long dateToConvert, String timezoneOffset){
        java.text.DateFormat format = SimpleDateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);/*new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");*/
        // java.util.Calendar cal = Calendar.getInstance(new
        // SimpleTimeZone(0, "GMT+05:30"));
        TimeZone gmtTime = TimeZone.getTimeZone("GMT"+timezoneOffset);


        format.setTimeZone(gmtTime);
        java.util.Date date1 = new Date(format.format(new Date(dateToConvert)));

        return date1;
    }

Hope this helps you. Cheers. :)



来源:https://stackoverflow.com/questions/10614771/java-simpledateformat-pattern-for-w3c-xml-dates-with-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!