Java Date Parse dateFromISO8601(String time)

Here you can find the source of dateFromISO8601(String time)

Description

date From ISO

License

Open Source License

Parameter

Parameter Description
time a parameter

Return

A date object representing the given ISO 8601 timestamp. If time is not a ISO 8601 formatted timestamp, the returned object is new Date(0) .

Declaration

public static Date dateFromISO8601(String time) 

Method Source Code

//package com.java2s;
/* Copyright (c) 2013 Jesper ?qvist <jesper@llbit.se>
 *
 * This file is part of Chunky./*from  w ww .ja  v a  2  s.co  m*/
 *
 * Chunky is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Chunky is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Chunky.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    /**
     * @param time
     * @return A date object representing the given ISO 8601 timestamp. If time is
     * not a ISO 8601 formatted timestamp, the returned object is
     * {@code new Date(0)}.
     */
    public static Date dateFromISO8601(String time) {
        if (time.length() < 6) {
            return new Date(0);
        }
        try {
            // insert "GMT"
            if (time.endsWith("Z")) {
                time = time.substring(0, time.length() - 1) + "GMT-00:00";
            } else {
                time = time.substring(0, time.length() - 6) + "GMT"
                        + time.substring(time.length() - 6, time.length());
            }
            // http://stackoverflow.com/a/10624878/1250278
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
            return dateFormat.parse(time);
        } catch (ParseException e) {
            return new Date(0);
        }
    }
}

Related

  1. convertUTCDateToLocal(String sDate, TimeZone timezone)
  2. convertXMLDate(String date)
  3. dateFromFilename(File file, Pattern fileNamePattern, DateFormat dateFormat)
  4. dateFromHourAndMinutes(final String pTime)
  5. dateFromISO8601(String iso)
  6. dateFromISODate(String isoDate)
  7. dateFromString(final String value)
  8. dateFromString(String date)
  9. dateFromString(String date, String pattern)