Java XML Date toJavaDate(String dateStr)

Here you can find the source of toJavaDate(String dateStr)

Description

Converts a date string in [datetime] format to a java date

License

Apache License

Parameter

Parameter Description
dateStr the string to convert

Return

the date, or null if the date is invalid

Declaration

public static Date toJavaDate(String dateStr) 

Method Source Code

//package com.java2s;
/*/*from ww w  .  j av  a2s.  c om*/
 * Copyright (C) 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import java.util.Date;

import java.util.regex.Pattern;
import javax.xml.bind.DatatypeConverter;

public class Main {
    /**
     * From the CAP spec:
     *
     * The date and time is represented in [dateTime] format
     * (e. g., "2002-05-24T16:49:00-07:00" for 24 May 2002 at
     * 16: 49 PDT).  Alphabetic timezone designators such as "Z"
     * MUST NOT be used.  The timezone for UTC MUST be represented
     * as "-00:00" or "+00:00"
     */
    // TODO(andriy): We handle fractional seconds (hundredths or thousands), but
    // because [dateTime] allows an arbitrary number of decimals, it would be
    // better to devise a more robust and flexible solution here.
    private static final Pattern DATE_PATTERN = Pattern
            .compile("[0-9]{4}-[01][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]"
                    + "(\\.[0-9]{2}([0-9])?)?([\\+|-])([01][0-9]:[0-5][0-9])");

    /**
     * Converts a date string in [datetime] format to a java date
     * @param dateStr the string to convert
     * @return the date, or null if the date is invalid
     */
    public static Date toJavaDate(String dateStr) {
        if (!DATE_PATTERN.matcher(dateStr).matches()) {
            return null;
        }
        try {
            return DatatypeConverter.parseDateTime(dateStr).getTime();
        } catch (IllegalArgumentException e) {
            return null;
        }
    }
}

Related

  1. printDate(java.util.Date dt)
  2. printDateTime(final Date date)
  3. printDateUpdatedType(Calendar value)
  4. string2millis(String lexicalXSDDateTime)
  5. toDate(String date)
  6. toTimeZone(String date, String toTimeZone)