Java Date ISO Parse parseIso8601(String time)

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

Description

Not working yet but this is supposed to parse an iso8601 date format

License

Open Source License

Parameter

Parameter Description
time date

Return

date

Declaration

public static Date parseIso8601(String time) 

Method Source Code

//package com.java2s;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.*;

public class Main {
    /**//from  ww  w .  j av a 2  s. c o m
     * Not working yet but this is supposed to parse an iso8601 date format
     *
     * @param time date
     * @return date
     */
    public static Date parseIso8601(String time) {
        String tmp = "((\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d))?(T(\\d\\d):(\\d\\d)(:(\\d\\d)?)?(.*)?)?";
        Pattern pattern = Pattern.compile(tmp);
        Matcher matcher = pattern.matcher(time);
        boolean ok = matcher.find();
        if (!ok) {
            System.err.println("No match:" + time);
            return null;
        }
        System.err.println("Time:" + time);
        for (int i = 1; i <= matcher.groupCount(); i++) {
            //      System.err.println("\t"+matcher.group(i));
        }
        int gidx = 1;
        gidx++;
        String year = str(matcher.group(gidx++), "0000");
        String month = str(matcher.group(gidx++), "01");
        String day = str(matcher.group(gidx++), "01");
        gidx++;
        String hh = str(matcher.group(gidx++), "00");
        String mm = str(matcher.group(gidx++), "00");
        gidx++;
        String ss = str(matcher.group(gidx++), "00");
        String tzd = str(matcher.group(gidx++), "GMT");
        if (tzd.equals("Z") || (tzd.length() == 0)) {
            tzd = "GMT";
        }

        //      System.err.println(year+"-"+month+"-"+day+"T"+hh+":"+mm+":"+ss+tzd);
        String format = "yyyy-MM-dd-HH-mm-ss-Z";
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern(format);
        String dateString = year + "-" + month + "-" + day + "-" + hh + "-"
                + mm + "-" + ss + "-" + tzd;
        try {
            Date dttm = sdf.parse(dateString);
            return dttm;
        } catch (Exception exc) {
            System.err.println("exc:" + exc);
            //      System.err.println(dateString);
            return null;
        }
    }

    /**
     * If s1 is null return dflt. Else return s1
     *
     * @param s1   string
     * @param dflt default
     * @return s1 or dflt
     */
    private static String str(String s1, String dflt) {
        return ((s1 != null) ? s1 : dflt);
    }
}

Related

  1. parseISO(String aIsoString)
  2. parseISO(String input)
  3. parseISO(String strValue)
  4. parseIso8601(String iso8601String)
  5. parseIso8601(String rawstr)
  6. parseISO8601Date(final String dateString)
  7. parseISO8601Date(String date)
  8. parseISO8601Date(String dateStr)
  9. parseIso8601Date(String datestr)