com.shekar.msrp.utils.DateUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.shekar.msrp.utils.DateUtils.java

Source

/*******************************************************************************
 * Software Name : RCS IMS Stack
 *
 * Copyright (C) 2010 France Telecom S.A.
 *
 * 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.
 ******************************************************************************/

package com.shekar.msrp.utils;

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

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

/**
 * 
 * @author chandrashekar.vuppal
 *
 */
public class DateUtils {

    /**
     * ISO 8601 date formats
     */
    private static SimpleDateFormat ISO8601DATEFORMAT[] = { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"),
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ") };

    /**
     * Encode a long date to string value in Z format (see RFC 3339)
     * 
     * @param date Date in milliseconds
     * @return String
     */
    public static String encodeDate(long date) {
        // Apply RFC3339 format using JODA-TIME
        DateTime dateTime = new DateTime(date, DateTimeZone.UTC);
        DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTime();
        String dateString = dateFormatter.print(dateTime);
        System.out.println("Server side date (RFC 3339): " + dateString);
        return dateString;
    }

    /**
     * Decode a string date to long value (see ISO8601 and RFC 3339)
     * 
     * @param date Date as string
     * @return Milliseconds
     */
    public static long decodeDate(String date) {
        long millis = -1;

        // Try to use ISO8601
        String normalizedDate = date.replaceAll("Z$", "+0000");
        for (int i = 0; millis == -1 && i < ISO8601DATEFORMAT.length; i++) {
            try {
                Date iso8601 = ISO8601DATEFORMAT[i].parse(normalizedDate);
                millis = iso8601.getTime();
            } catch (ParseException ex) {
                // Try next format
            }
        }

        // If still not valid format is found let's try RFC3339
        if (millis == -1) {
            Date t = null;
            try {
                t = parseRFC3339Date(date);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            millis = t.getTime();
        }

        return millis;
    }

    static Date parseRFC3339Date(String datestring) throws java.text.ParseException, IndexOutOfBoundsException {
        Date d = new Date();

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

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

        //step two, remove the colon from the timezone offset
        secondpart = secondpart.substring(0, secondpart.indexOf(':'))
                + secondpart.substring(secondpart.indexOf(':') + 1);
        datestring = firstpart + secondpart;
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");//spec for RFC3339      
        try {
            d = s.parse(datestring);
        } catch (java.text.ParseException pe) {//try again with optional decimals
            s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ");//spec for RFC3339 (with fractional seconds)
            s.setLenient(true);
            d = s.parse(datestring);
        }
        return d;
    }

    //some testing stuff in main()
    public static void main(String[] args) throws java.text.ParseException {
        System.out.println(parseRFC3339Date("2007-05-01T15:43:26-07:00"));
        System.out.println(parseRFC3339Date("2007-05-01T15:43:26.3-07:00"));
        System.out.println(parseRFC3339Date("2007-05-01T15:43:26.3452-07:00"));
        System.out.println(parseRFC3339Date("2007-05-01T15:43:26.3452Z"));
        System.out.println(parseRFC3339Date("2007-05-01T15:43:26.3Z"));
        System.out.println(parseRFC3339Date("2007-05-01T15:43:26Z"));
    }
}