Frage

    

Diese Frage bereits eine Antwort hier:

         

Was wäre der einfachste Weg, um dieses Datumsformat unten in Java zu analysieren:

2010-09-18T10:00:00.000+01:00

ich die Date api in Java lesen und konnte nicht eine Methode, die einen String oder sogar diese Art von Datumsformat als paremeter zu parsen finden? Wenn ich von Parse bedeuten ich meine, ich will das „Datum (Tag Monat und Jahr)“, „Zeit“ und „Zeitzone“ in separate String-Objekte extrahieren.

Vielen Dank im Voraus

War es hilfreich?

Lösung

Eine andere Antwort, da Sie scheinen auseinander auf einfach zu zerreißen die String fokussiert werden (keine gute Idee, IMHO.) Nehmen wir an, die Zeichenkette gültig ist ISO8601. Können Sie davon ausgehen, es wird immer in Form sein, das Sie zitieren, oder ist es 8601 nur gültig? Wenn letzteres der Fall, müssen Sie mit einem Bündel von Szenarien wie diese Jungs haben .

Die Regex sie kam 8601 Alternativen zu validieren ist:

^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])
 (-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])
 ((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?
 ([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$ 

Herauszufinden, wie die richtigen Einfanggruppen herauszukitzeln macht mich benebelt. Dennoch wird die folgende für Ihren speziellen Fall arbeiten:

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Regex8601
{
  static final Pattern r8601 = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})T((\\d{2}):"+
                               "(\\d{2}):(\\d{2})\\.(\\d{3}))((\\+|-)(\\d{2}):(\\d{2}))");


  //2010-09-18T10:00:00.000+01:00

  public static void main(String[] args)
  {
    String thisdate = "2010-09-18T10:00:00.000+01:00";
    Matcher m = r8601.matcher(thisdate);
    if (m.lookingAt()) {
      System.out.println("Year: "+m.group(1));
      System.out.println("Month: "+m.group(2));
      System.out.println("Day: "+m.group(3));
      System.out.println("Time: "+m.group(4));
      System.out.println("Timezone: "+m.group(9));
    } else {
      System.out.println("no match");
    }
  }
}

Andere Tipps

Wenn Sie etwas nicht-trivial mit Datums- und Zeitangaben machen, empfehlen die Verwendung von JodaTime . Siehe diese umfangreiche SO Diskussion , einschließlich ISO8601 . Siehe auch " Soll ich nativen Daten / Zeit ... ".

Hier ist ein Beispiel-Code-Snippet, genommen von diesem Beispiel wenn Sie JDK SimpleDateFormat verwenden möchten.

// 2004-06-14T19:GMT20:30Z
// 2004-06-20T06:GMT22:01Z

// http://www.cl.cam.ac.uk/~mgk25/iso-time.html
//    
// http://www.intertwingly.net/wiki/pie/DateTime
//
// http://www.w3.org/TR/NOTE-datetime
//
// Different standards may need different levels of granularity in the date and
// time, so this profile defines six levels. Standards that reference this
// profile should specify one or more of these granularities. If a given
// standard allows more than one granularity, it should specify the meaning of
// the dates and times with reduced precision, for example, the result of
// comparing two dates with different precisions.

// The formats are as follows. Exactly the components shown here must be
// present, with exactly this punctuation. Note that the "T" appears literally
// in the string, to indicate the beginning of the time element, as specified in
// ISO 8601.

//    Year:
//       YYYY (eg 1997)
//    Year and month:
//       YYYY-MM (eg 1997-07)
//    Complete date:
//       YYYY-MM-DD (eg 1997-07-16)
//    Complete date plus hours and minutes:
//       YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
//    Complete date plus hours, minutes and seconds:
//       YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
//    Complete date plus hours, minutes, seconds and a decimal fraction of a
// second
//       YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)

// where:

//      YYYY = four-digit year
//      MM   = two-digit month (01=January, etc.)
//      DD   = two-digit day of month (01 through 31)
//      hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
//      mm   = two digits of minute (00 through 59)
//      ss   = two digits of second (00 through 59)
//      s    = one or more digits representing a decimal fraction of a second
//      TZD  = time zone designator (Z or +hh:mm or -hh:mm)
public static Date parse( String input ) throws java.text.ParseException 
{
  //NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks
  //things a bit.  Before we go on we have to repair this.
  SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssz" );

  //this is zero time so we need to add that TZ indicator for 
  if ( input.endsWith( "Z" ) ) {
    input = input.substring( 0, input.length() - 1) + "GMT-00:00";
  } else {
    int inset = 6;

    String s0 = input.substring( 0, input.length() - inset );
    String s1 = input.substring( input.length() - inset, input.length() );    

    input = s0 + "GMT" + s1;
  }

  return df.parse( input );        
}

Dieses Datum ist in ISO 8601 . Hier ein Link zu einem Parser speziell für dieses Format , die die verwendet Java Simple Parsen intern APIs.

Sie sollten verwenden Simple ,

Beispiele finden und hier um loszulegen

Sie können mit javax.xml.datatype.DatatypeFactory#newXMLGregorianCalendar(String lexicalRepresentation) ( API-Dokumentation ). Der zurück XMLGregorianCalendar gibt Ihnen alle die einzelnen Felder zugreifen zu können.

Verwenden Sie Simple , mit der Muster als yyy-MM-dd'T'HH:mm:ss.SSSZ


Aktualisieren Simple wird nicht funktionieren mit ISO 8601 Datumsformat. Vielmehr verwenden, JodaTime statt. Es bietet ISOChronology dass entspricht ISO 8601 .

Kurzbeispiel finden Sie auf SO finden .

Die einfachste Lösung ist dies:

Date date = null;
SimpleDateFormat isoFormatWithMillis = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
try {
    date = isoFormatWithMillis.parse("2010-09-18T10:00:00.000+01:00");
} catch (ParseException e) {
    e.printStackTrace();
}
System.out.println(date);

Dieses Sat Sep 18 11:00:00 CEST 2010 gedruckt wird.

Wenn Sie mit Java 7 oder früher können Sie bezeichnen dies

scroll top