Java Parse Date parseDate(final String dateStr)

Here you can find the source of parseDate(final String dateStr)

Description

Attempts to parse given date string using patterns described https://tools.ietf.org/html/rfc6991#page-11 with exception that ONLY UTC patterns are accepted.

License

Open Source License

Parameter

Parameter Description
dateStr date string to parse

Exception

Parameter Description
IllegalArgumentException if none patterns matched given input

Declaration

public static Date parseDate(final String dateStr) 

Method Source Code

//package com.java2s;
/*/*from www .  j  a  v  a 2  s. c o m*/
 * Copyright (C) 2016 AT&T Intellectual Property. All rights reserved.
 * Copyright (c) 2016 Brocade Communications Systems, Inc. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.TimeZone;

public class Main {
    private static final TimeZone TZ_UTC = TimeZone.getTimeZone("UTC");
    private static final String[] DATE_AND_TIME_FORMATS = { "yyyy-MM-dd'T'HH:mm:ss'Z'",
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" };

    /**
     * Attempts to parse given date string using patterns described
     * https://tools.ietf.org/html/rfc6991#page-11 with exception that ONLY UTC
     * patterns are accepted.
     *
     * @param dateStr
     *            date string to parse
     * @return {@link Date}
     * @throws IllegalArgumentException
     *             if none patterns matched given input
     */
    public static Date parseDate(final String dateStr) {
        for (final String fmt : DATE_AND_TIME_FORMATS) {
            try {
                // constructing SimpleDateFormat instances can be costly,
                // but this utility method is rarely used (and is private to
                // application).
                final SimpleDateFormat sdf = new SimpleDateFormat(fmt);
                sdf.setTimeZone(TZ_UTC);
                return sdf.parse(dateStr);
            } catch (ParseException e) {
                // ignore
            }
        }
        throw new IllegalArgumentException(
                "Unrecognized DateAndTime value : " + dateStr + " (only UTC date is accepted)");
    }
}

Related

  1. parseDate(final String date)
  2. parseDate(final String date)
  3. parseDate(final String date)
  4. parseDate(final String date, final List patterns)
  5. parseDate(final String date, final String format)
  6. parseDate(final String dateString)
  7. parseDate(final String pDate)
  8. parseDate(final String revision)
  9. parseDate(final String source)