質問

この質問にはすでに答えがあります:

以下の日付形式を Java で解析する最も簡単な方法は何でしょうか?

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

JavaでDateFormat APIを読んだのですが、文字列またはこのタイプの日付形式を解析するパラメータとして受け取るメソッドが見つかりませんでしたか?解析とは、「日付(日、月、年)」、「時刻」、「タイムゾーン」を別の文字列オブジェクトに抽出することを意味します。

前もって感謝します

役に立ちましたか?

解決

別の答えは、あなたは単純に引き裂くことに焦点を当てているようです。 String (私見ですが、良い考えではありません。) 文字列が有効な ISO8601 であると仮定しましょう。そうなると想定できますか いつも あなたが引用した形式になっていますか、それともそれは単に有効な8601ですか?後者の場合は、次のような多くのシナリオに対処する必要があります。 この人たちはやった.

8601 の代替を検証するために彼らが考え出した正規表現は次のとおりです。

^([\+-]?\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)?)?)?)?$ 

正しいキャプチャ グループを特定する方法を考えると、うっとうしくなります。ただし、特定のケースでは次のことが機能します。

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");
    }
  }
}

他のヒント

は、日付と時刻との非自明な何かをやっている場合は、 JodaTimeするを使用することをお勧めします。この大規模なSOディスカッションをhref="https://stackoverflow.com/questions/3709870/how-do-libraries-in-different-programming-languages-handle-date-time-timestamp"> ISO8601 を含みます。参照してください<のhref = "https://stackoverflow.com/questions/589870/should-i-use-java-date-and-time-classes-or-go-with-a-3rd-party-library-like -joda ">" SHOULD Iは、ネイティブデータ/時間を使用して... "するます。

はここでは、この例から採取したサンプルコードスニペットは、です>、あなたはJDKのSimpleDateFormatを使用する場合。

// 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 );        
}

この日は、 ISO 8601形式のです。ここでの使用しています。この形式のにパーサ特定へのリンク内部のAPIを解析するJavaのSimpleDateFormat。

使用する必要があります SimpleDateFormat,

例を見つける ここ そして ここ 始めるために。

使用 SimpleDateFormat, 、パターンは次のようになります yyy-MM-dd'T'HH:mm:ss.SSSZ


アップデート SimpleDateFormat は ISO 8601 日付形式では機能しません。むしろ使って、 ジョーダタイム その代わり。それは提供します ISO年表 ISO 8601に準拠しています。

簡単な例は次の場所にあります。 それで.

は最も簡単な解決策はこれです

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);

このはSat Sep 18 11:00:00 CEST 2010を印刷します。

Java 7 以前を使用している場合は、これを参照してください。 役職.

Java 8 を使用している場合は、次のようにすることができます。

    DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
    TemporalAccessor accessor = timeFormatter.parse("2015-10-27T16:22:27.605-07:00");

    Date date = Date.from(Instant.from(accessor));
    System.out.println(date);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top