代码之家  ›  专栏  ›  技术社区  ›  Jono

在Java中解析这种类型的日期格式?[副本]

  •  2
  • Jono  · 技术社区  · 15 年前

    这个问题已经有了答案:

    在Java中解析这个日期格式最简单的方法是什么?:

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

    我读了Java中的DATEFraseAPI,却找不到一种方法,它把字符串或甚至这种类型的日期格式作为一个参数来解析。当我的意思是解析时,我的意思是要将“日期(日、月、年)”、“时间”和“时区”提取成单独的字符串对象。

    提前谢谢

    8 回复  |  直到 10 年前
        1
  •  4
  •   andersoj    15 年前

    另一个答案,因为你似乎只专注于撕 String 另外(不是个好主意,imho。)让我们假设字符串是有效的iso8601。你能假定它会 总是 以你引用的格式,还是仅仅是8601?如果是后者,您必须处理一系列场景 these guys did .

    他们提出的用于验证8601个备选方案的regex是:

    ^([\+-]?\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");
        }
      }
    }
    
        2
  •  3
  •   Community Mohan Dere    8 年前

    如果您在日期和时间方面做了一些非常重要的事情,建议使用 JodaTime . 见 this extensive SO discussion ,包括 ISO8601 . 另请参见 "Should I use native data/time..."

    下面是一个示例代码片段,取自 this example ,如果您想使用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 );        
    }
    
        3
  •  2
  •   orangepips 111111    15 年前

    这个日期在 ISO 8601 format . 这里是 a link to a parser specific to this format 在内部使用Java SimuleDead格式解析API。

        4
  •  1
  •   Johnbabu Koppolu    15 年前

    你应该用 SimpleDateFormat ,

    查找示例 here here 开始吧。

        5
  •  0
  •   jarnbjo    15 年前

    你可以用 javax.xml.datatype.DatatypeFactory#newXMLGregorianCalendar(String lexicalRepresentation) ( API docs )返回的xmlGregorianCalendar允许您访问所有单独的字段。

        6
  •  0
  •   Community Mohan Dere    8 年前

    使用 SimpleDateFormat ,图案为 yyy-MM-dd'T'HH:mm:ss.SSSZ


    更新 SimpleDateFormat无法与ISO 8601日期格式一起使用。而是使用, JodaTime 相反。它提供 ISOChronology 符合ISO 8601。

    可以在上找到简短的示例 SO

        7
  •  0
  •   Vladimir Prudnikov    11 年前

    最简单的解决方案是:

    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

        8
  •  0
  •   Community Mohan Dere    8 年前

    如果您使用Java 7或更早,您可以参考此 post

    如果你正在使用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);
    
    推荐文章