Java Date RFC Format get3339Date(String rfc3339Date)

Here you can find the source of get3339Date(String rfc3339Date)

Description

get Date

License

Apache License

Declaration

public static Date get3339Date(String rfc3339Date) 

Method Source Code


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

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

public class Main {
    public static Date get3339Date(String rfc3339Date) {
        Date date = null;//  w w w .  j a v a2 s.  c  om

        try {
            // if there is no time zone, we don't need to do any special parsing.
            if (rfc3339Date.endsWith("Z")) {
                try {
                    // spec for RFC3339
                    final SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    date = s.parse(rfc3339Date);
                } catch (final java.text.ParseException pe) { // try again with optional decimals
                    // spec for RFC3339 (with fractional seconds)
                    final SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
                    s.setLenient(true);
                    date = s.parse(rfc3339Date);
                }

                return date;
            }

            // step one, split off the timezone.
            final String firstpart = rfc3339Date.substring(0, rfc3339Date.lastIndexOf('-'));
            String secondpart = rfc3339Date.substring(rfc3339Date.lastIndexOf('-'));

            // step two, remove the colon from the timezone offset
            secondpart = secondpart.substring(0, secondpart.indexOf(':'))
                    + secondpart.substring(secondpart.indexOf(':') + 1);
            rfc3339Date = firstpart + secondpart;

            // spec for RFC3339
            SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            try {
                date = s.parse(rfc3339Date);
            } catch (final java.text.ParseException pe) {// try again with optional decimals
                // spec for RFC3339 (with fractional seconds)
                s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");
                s.setLenient(true);
                date = s.parse(rfc3339Date);
            }
        } catch (final ParseException e) {
            // return nothing
        }

        return date;
    }
}

Related

  1. getRFC1123Date()
  2. getRfc1123DateFormat()
  3. getRFC2616Date(Date date)
  4. getRFC3339String(Calendar timestamp)