Java Date ISO Parse parseISO8601Date(String s)

Here you can find the source of parseISO8601Date(String s)

Description

parse ISO Date

License

Apache License

Declaration

public static Date parseISO8601Date(String s) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
    public static final String ISO8601DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    public static final String ISO8601DATE_WITH_MILLS_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    public static final String ISO8601DATE_WITH_ZONE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssX";
    public static final String ISO8601DATE_WITH_ZONE_MILLS_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
    public static final String DATE_FORMAT = "yyyy-MM-dd";
    public static final int ISO8601DATE_FORMAT_VALUE_LENGTH = ISO8601DATE_FORMAT.length() - 4;

    public static Date parseISO8601Date(String s) {
        if (s == null || s.isEmpty()) {
            return null;
        }//from   w w w . ja v  a 2  s .  c  om
        try {
            Date date = null;
            if (s.charAt(s.length() - 1) == 'Z') {
                String format = (s.length() == ISO8601DATE_FORMAT_VALUE_LENGTH) ? ISO8601DATE_FORMAT
                        : ISO8601DATE_WITH_MILLS_FORMAT;
                DateFormat dateFormat = new SimpleDateFormat(format);
                dateFormat.setTimeZone(GMT_TIMEZONE);
                date = dateFormat.parse(s);
            } else if (s.length() == DATE_FORMAT.length()) {
                DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
                // TODO use system TimeZone instead
                dateFormat.setTimeZone(GMT_TIMEZONE);
                date = dateFormat.parse(s);
            } else if (s.indexOf('.') > 0) {
                date = new SimpleDateFormat(ISO8601DATE_WITH_ZONE_MILLS_FORMAT).parse(s);
            } else {
                date = new SimpleDateFormat(ISO8601DATE_WITH_ZONE_FORMAT).parse(s);
            }
            return date;
        } catch (ParseException e) {
            throw new RuntimeException("Failed to parseISO8601Date", e);
        }
    }
}

Related

  1. parseISO8601Date(String dateString)
  2. parseISO8601Date(String dateString)
  3. parseISO8601Date(String dateString)
  4. parseIso8601Date(String dateString)
  5. parseISO8601Date(String encoded, Date fallback)
  6. parseIso8601Date(String strDate)
  7. parseISO8601DateString(String dateString)
  8. parseIso8601DateTimeOrDate(String datestr)
  9. parseISO8601String(String dateString)