Java Parse Date parseDate(String date)

Here you can find the source of parseDate(String date)

Description

Parses a date of the form 1969-12-31T21:00:00-03:00, or 2008-02-13T18:54:29.147-03:00.

License

Open Source License

Parameter

Parameter Description
date the string to parse

Return

the corresponding date, or null if t

Declaration

public static Date parseDate(String date) 

Method Source Code

//package com.java2s;
/**/* w  w w .  ja  va  2s .  c  om*/
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
 *
 * 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.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {
    private static final SimpleDateFormat dateFormatMil = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    private static final SimpleDateFormat dateFormatNoMil = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ssZ");

    /**
     * Parses a date of the form 1969-12-31T21:00:00-03:00, or 2008-02-13T18:54:29.147-03:00.
     * If the string is null or there is a problem parsing the date, returns null.
     *
     * @param date the string to parse
     * @return the corresponding date, or null if t
     */
    public static Date parseDate(String date) {
        if (date == null) {
            return null;
        }
        // REST writes dates time zone with ':', somthing like -3:00
        // to parse it they should be removed
        int index = date.lastIndexOf(":");
        date = date.substring(0, index) + date.substring(index + 1);
        Date d = null;
        try {
            if (date.length() == 24) {
                d = dateFormatNoMil.parse(date);
            } else {
                d = dateFormatMil.parse(date);
            }
        } catch (ParseException e) {
            // can't parse it, return null
        }
        return d;
    }
}

Related

  1. parseDate(String d)
  2. parseDate(String d)
  3. parseDate(String d)
  4. parseDate(String datastr, String pattern)
  5. parseDate(String date)
  6. parseDate(String date)
  7. parseDate(String date)
  8. parseDate(String date)
  9. parseDate(String date)